3.16. Executing Cypher queries from Java

This section describes how to use the Cypher query language with 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, we will add some data:

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

        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];

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 do not 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.

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

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]

Use the following to fetch the result items from a single column. In this case, we will 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 is 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.

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 Neo4j Cypher Manual.