连接到 Neo4j

Cypher® Builder 库帮助您构建 Cypher 查询,但将这些查询发送到 Neo4j 必须通过 Neo4j driver 单独完成。本页演示了如何做到这一点。

设置项目

  1. 按照 Installation 中的说明初始化您的项目。

  2. 要连接到 Neo4j,请确保在您的 NodeJS 项目中已安装 @neo4j/cypher-builderneo4j-driver 两个包。

    npm install @neo4j/cypher-builder neo4j-driver

    本例使用 movies 数据集。或者,您可以使用以下 Cypher 语句创建数据。

    CREATE(:Movie {title: "The Matrix"})
    CREATE(:Movie {title: "The Terminal"})

初始化驱动

installation JavaScript 文件中添加以下代码以初始化驱动。

import Cypher from "@neo4j/cypher-builder";
import neo4j from "neo4j-driver";

const driver = neo4j.driver("neo4j://", neo4j.auth.basic("neo4j", "password"));

构建 Cypher 查询

您可以使用 Cypher 对象构建任意查询。例如:

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

这将生成如下查询:

MATCH (this0:Movie)
RETURN this0.title AS title

执行查询

在查询对象上使用 .build 可生成 Cypher 查询以及需要传递给 neo4j-driver 的参数。

const { cypher, params } = query.build();
const { records } = await driver.executeQuery(cypher, params);

完成后,请关闭驱动连接。

await driver.close();

消费结果

records 对象的使用方式请参阅 JavaScript Driver 文档 中的说明。

for (const record of records) {
    console.log(record.get("title"));
}

对于 Setup the project 中的示例数据,结果如下:

The Matrix
The Terminal

结论

您的脚本应如下所示:

import Cypher from "@neo4j/cypher-builder";
import neo4j from "neo4j-driver";

const driver = neo4j.driver("neo4j://", neo4j.auth.basic("neo4j", "password"));

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

const { cypher, params } = query.build();
const { records } = await driver.executeQuery(cypher, params);

await driver.close();

for (const record of records) {
    console.log(record.get("title"));
}
© . This site is unofficial and not affiliated with Neo4j, Inc.