32.16. Execute Cypher Queries from Java

[Tip]Tip

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" );
    tx.success();
}

Execute a query:

try ( Transaction ignored = db.beginTx();
      Result result = db.execute( "match (n {name: 'my node'}) return n, n.name" ) )
{
    while ( result.hasNext() )
    {
        Map<String,Object> row = result.next();
        for ( Entry<String,Object> column : row.entrySet() )
        {
            rows += column.getKey() + ": " + column.getValue() + "; ";
        }
        rows += "\n";
    }
}

In the above example, we also show how to iterate over the rows of the Result.

The code will generate:

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

When using an Result, you should consume the entire result (iterate over all rows using next(), iterating over the iterator from columnAs() or calling for example resultAsString()). Failing to do so will not properly clean up resources used by the Result object, leading to unwanted behavior, such as leaking transactions. In case you don’t want to iterate over all of the results, make sure to invoke close() as soon as you are done, to release the resources tied to the result.

[Tip]Tip

Using a try-with-resources statement will make sure that the result is closed at the end of the statement. This is the recommended way to handle results.

You can also get a list of the columns in the result like this:

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

This gives us:

[n, n.name]

To fetch the result items from a single column, do like below. In this case we’ll have to read the property from the node and not from the result.

Iterator<Node> n_column = result.columnAs( "n" );
for ( Node node : Iterators.asIterable( n_column ) )
{
    nodeResult = node + ": " + node.getProperty( "name" );
}

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

Node[0]: my node

Only use this if the result only contains a single column, or you are only interested in a single column of the result.

[Note]Note

resultAsString(), writeAsStringTo(), columnAs() cannot be called more than once on the same Result object, as they consume the result. In the same way, part of the result gets consumed for every call to next(). 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 Result.

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, Basic Data Modeling Examples.