Introduction
You can use the executableQuery() method to create one-off Cypher statements that return a small number of records.
The execute method fetches a list of records and loads them into memory.
final String cypher = """
MATCH (p:Person {name: $name})-[r:ACTED_IN]->(m:Movie)
RETURN m.title AS title, r.role AS role
""";
final String name = "Tom Hanks";
var result = driver.executableQuery(cypher)
.withParameters(Map.of("name", name))
.execute();You can use the App.java file throughout the course to experiment and run any code snippets.
-
The
executableQuerymethod expects a Cypher statement as a string as the first argument. -
Parameters can be passed as a map using the
withParameters()method. -
The
execute()method runs the query and returns the result.
Using Parameters
It is good practice to use parameters in your queries to avoid malicious code being injected into your Cypher statement.
Handling the Result
The execute() method returns an EagerResult object that contains:
-
A list of
Recordobjects -
ResultSummaryof the query execution -
A list of keys specified in the
RETURNclause
var records = result.records(); // (1)
var summary = result.summary(); // (2)
var keys = result.keys(); // (3)
System.out.println(records);
System.out.println(summary);
System.out.println(keys);Accessing results
Each row returned by the query is a Record object. The Record object provides access to the data returned by the query.
You can access any item in the RETURN clause using the get method.
// RETURN m.title AS title, r.role AS role
var records = result.records();
records.forEach(r -> {
System.out.println(r.get("title"));
System.out.println(r.get("role"));
});Reading and writing
By default, executableQuery() runs in WRITE mode. In a clustered environment, this sends all queries to the cluster leader, putting unnecessary load on the leader.
When you’re only reading data, you can optimize performance by configuring the query to READ mode.
This distributes your read queries across all cluster members.
import org.neo4j.driver.RoutingControl;
var result = driver.executableQuery(cypher)
.withParameters(Map.of("name", name))
.withConfig(QueryConfig.builder()
.withRouting(RoutingControl.READ)
.build())
.execute();Check your understanding
Summary
In this lesson, you learned how to execute one-off Cypher statements using the executableQuery() method and access the results.