Executing Cypher statements

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.

Java
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.

  1. The executableQuery method expects a Cypher statement as a string as the first argument.

  2. Parameters can be passed as a map using the withParameters() method.

  3. 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:

  1. A list of Record objects

  2. ResultSummary of the query execution

  3. A list of keys specified in the RETURN clause

Java
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.

Java
// 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.

Java
import org.neo4j.driver.RoutingControl;

var result = driver.executableQuery(cypher)
    .withParameters(Map.of("name", name))
    .withConfig(QueryConfig.builder()
                .withRouting(RoutingControl.READ)
                .build())
    .execute();

Summary

In this lesson, you learned how to execute one-off Cypher statements using the executableQuery() method and access the results.