32.12. Execute Cypher Queries from Java


The full source code of the example: JavaQuery.java

In Java, you can use the Cypher query language as per the example below. First, let’s add some data.

GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );

try ( Transaction tx = db.beginTx(); )
    Node myNode = db.createNode();
    myNode.setProperty( "name", "my node" );

Execute a query:

ExecutionEngine engine = new ExecutionEngine( db );

ExecutionResult result;
try ( Transaction ignored = db.beginTx() )
    result = engine.execute( "match (n {name: 'my node'}) return n, n.name" );

Keep the ExecutionEngine around, don’t create a new one for each query!

The result will be:

| n                       | n.name    |
| Node[0]{name:"my node"} | "my node" |
1 row

The classes used here are from the org.neo4j.cypher.javacompat package, not org.neo4j.cypher, see link to the Java API below.

You can get a list of the columns in the result:

List<String> columns = result.columns();

This contains:

[n, n.name]

To fetch the result items from a single column, do like this:

Iterator<Node> n_column = result.columnAs( "n" );
for ( Node node : IteratorUtil.asIterable( n_column ) )
    // note: we're grabbing the name property from the node,
    // not from the n.name in this case.
    nodeResult = node + ": " + node.getProperty( "name" );

In this case there’s only one node in the result:

Node[0]: my node

To get all columns, do like this instead:

for ( Map<String, Object> row : result )
    for ( Entry<String, Object> column : row.entrySet() )
        rows += column.getKey() + ": " + column.getValue() + "; ";
    rows += "\n";

This outputs:

n.name: my node; n: Node[0];

dumpToString(), columnAs() and iterator() cannot be called more than once on the same ExecutionResult object. You should instead use only one and if you need the facilities of the other methods on the same query result instead create a new ExecutionResult.


When using an ExecutionResult, you’ll need to exhaust it by using any of the iterating methods (columnAs() and iterator()) on it. Failing to do so will not properly clean up resources used by the ExecutionResult, leading to unwanted behavior, such as leaking transactions.

For more information on the Java interface to Cypher, see the Java API.

For more information and examples for Cypher, see Cypher Query Language and Chapter 5, Data Modeling Examples.