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 page demonstrates how you can do that.
Setup the project
-
Initialize your project by following the instructions in Installation.
-
To connect to Neo4j, make sure you have both
@neo4j/cypher-builderandneo4j-driverinstalled in your NodeJS project:npm install @neo4j/cypher-builder neo4j-driverFor this example, the movies data set is used. Alternatively, you can create entries with the following Cypher®:
CREATE(:Movie {title: "The Matrix"}) CREATE(:Movie {title: "The Terminal"})
Initialize the driver
Add the following lines to the installation JavaScript file to initialize the driver:
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 example:
const movie = new Cypher.Node();
const query = new Cypher.Match(new Cypher.Pattern(movie, { labels: ["Movie"] })).return([
movie.property("title"),
"title",
]);
This creates the following query:
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"));
}
For the example data from Setup the project, this yields:
The Matrix
The Terminal
Conclusion
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"));
}