变量

在 Cypher® 中可以使用变量来引用模式的部分并保存值。例如

MATCH (m:Movie)
RETURN m

变量 m 引用模式 (:Movie) 中匹配到的节点。随后返回该节点。

编写动态 Cypher 查询可能很具挑战性,因为生成的变量需要具有唯一名称以正确引用值。使用 Cypher Builder 的优势在于 JavaScript 引用消除了跟踪变量名称的需求,从而提供了另一层抽象。

类型

Cypher Builder 区分四种变量类型

  • Node: 保存对模式中匹配到的节点的引用。

  • Relationship: 保存对模式中关系的引用。

  • Variable: 通用变量引用。

  • Path: 用于保存路径的变量。

所有 Cypher Builder 变量都是指向 Cypher 变量的虚拟引用,后者将在生成时转换为唯一名称。

定义变量

可以使用以下方式定义任意 Cypher 变量

const myVar = new Cypher.Variable();

随后可以在任何支持变量的子句中将该变量用作表达式,例如

const myVar = new Cypher.Variable();
const query = new Cypher.Return(myVar)
RETURN var0

var0 名称会在调用 .build() 时自动生成,以避免名称冲突。如果重复使用该变量,生成的 Cypher 中将使用相同的名称,例如

const myVar = new Cypher.Variable();
const query = new Cypher.With(myVar).return(myVar);
WITH var0
RETURN var0

每次创建的变量实例都会对应一个不同的名称

const withVar = new Cypher.Variable();
const returnVar = new Cypher.Variable();
const query = new Cypher.With(withVar).return(returnVar);
WITH var0
RETURN var1

节点和关系

节点和关系是变量的语法糖。它们可以在 模式 中使用,例如

const movie = new Cypher.Node();
const relationship = new Cypher.Relationship();

const pattern = new Cypher.Pattern(movie, { labels: ["Movie"] }).related(relationship, { type: "ACTED_IN" }).to();
const match = new Cypher.Match(pattern).return(movie);
MATCH (this0:Movie)-[this1:ACTED_IN]->()
RETURN this0

在此示例中,节点变量 movie 被创建并随后在 MATCHRETURN 子句中使用。

在翻译后的 Cypher 中,你可以看到节点变量被转换为 Cypher 变量 this0,而关系被分配为 this1。这些名称并未在你的 JavaScript 代码中定义,而是在使用 .build() 构建查询时自动生成。传递给 NodeRelationship 变量的标签和类型会被用于模式中。

Path

路径变量可用于模式中的路径赋值,例如

MATCH p0 = (this1)-[this2:ACTED_IN]->(this3)
RETURN p0

要分配路径变量,请在相应的模式中使用方法 .assignTo 并传入一个 new PathVariable() 实例

const path = new Cypher.PathVariable();

const query = new Cypher.Match(pattern.assignTo(path)).return(path);

具名变量

默认情况下,变量没有名称;在构建时会生成唯一的名称/ID 以避免冲突。不过在某些情况下,你可能需要生成具有特定名称的查询。为此,所有变量类型都必须有对应的 Named 类,例如

  • NamedVariable

  • NamedNode

  • NamedRelationship

  • NamedPathVariable

这些类的使用方式与普通变量相同,只是创建时必须提供名称

const movie = new Cypher.NamedNode("n");
const match = new Cypher.Match(movie, { labels: ["Movie"] }).return(movie);
MATCH (n:Movie)
RETURN n

属性

节点或映射等变量可能包含属性。要在生成的 Cypher 中访问这些属性,可在变量上使用方法 .property

const movie = new Cypher.Node()
const query = new Cypher.Match(movie, { labels: ["Movie"] }).return(movie.property("title"));
MATCH(this0:Movie)
RETURN this0.title

嵌套属性

嵌套属性也可以通过传入多个参数或链式调用 .property 来访问

new Cypher.Variable().property("movie", "title");
new Cypher.Variable().property("movie").property("title")

在这两种情况下,生成的 Cypher 应该类似于下面的形式

var0.movie.title

表达式

表达式同样可以用作属性键,以实现动态属性访问

const movie = new Cypher.Node()

const movieProperty = movie.property(Cypher.plus(new Cypher.Param("ti"), new Cypher.Literal("tle")))
const query = new Cypher.Match(movie, { labels: ["Movie"] }).return(movieProperty);

查询会自动为表达式添加方括号([])记法,以安全地执行该表达式

MATCH(this0:Movie)
RETURN this0[($param0 + $param1)]

索引

和属性一样,索引也可以通过方法 .index 进行访问

new Cypher.Variable().index(2);
var0[2]
© . This site is unofficial and not affiliated with Neo4j, Inc.