Connecting to Neo4j
The Cypher® Builder library helps you compose Cypher queries, but sending these to Neo4j must be done separately through a Neo4j driver. This tutorial demonstrates how you can do that.
Setup the project
-
Initialize your project by following the instructions in the Installation page.
-
To connect to Neo4j, make sure you have both
@neo4j/cypher-builder
andneo4j-driver
installed in your NodeJS project:npm install @neo4j/cypher-builder neo4j-driver
For this example, the Movies dataset is used. Alternatively, you can create entries with the following Cypher examples:
CREATE(:Movie {title: "The Matrix"}) CREATE(:Movie {title: "The Terminal"})
Initialize the driver
Add the following lines to the JavaScript file created in the Installation step to initialize the driver:```
I think the link to the JS manual makes it a bit confusing here because the instructions are also featured below, so if that makes sense, removing that notion can be a bit more clarifying.
import Cypher from "@neo4j/cypher-builder";
import neo4j from "neo4j-driver";
const driver = neo4j.driver("neo4j://localhost", neo4j.auth.basic("neo4j", "password"));
Construct your Cypher query
You can compose any query by using the Cypher object. For instance, this query:
const movie = new Cypher.Node();
const query = new Cypher.Match(new Cypher.Pattern(movie, { labels: ["Movie"] })).return([
movie.property("title"),
"title",
]);
This will translate to:
MATCH (this0:Movie)
RETURN this0.title AS title
Execute the query
Use .build
in the query object to generate the Cypher query and the necessary parameters to pass to neo4j-driver
:
const { cypher, params } = query.build();
const { records } = await driver.executeQuery(cypher, params);
When you are finished, close the driver connection:
await driver.close();
Consume the results
The records
object can be consumed as explained in the JavaScript Driver documentation:
for (const record of records) {
console.log(record.get("title"));
}
With the previous example data, this should output:
The Matrix
The Terminal
Conclusion
After following the steps here described, your script should look like this:
import Cypher from "@neo4j/cypher-builder";
import neo4j from "neo4j-driver";
const driver = neo4j.driver("neo4j://localhost", 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"));
}