Cypher queries

In Java, you can use the Cypher query language as per the example below.

The source code for the examples can befound at:

First, you can add some data:

DatabaseManagementService managementService = new DatabaseManagementServiceBuilder( databaseDirectory ).build();
GraphDatabaseService db = managementService.database( DEFAULT_DATABASE_NAME );

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

Execute a query:

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

In this example, you can also see how to iterate over the rows of the org.neo4j.graphdb.Result.

The code will generate:

n: Node[0]; my node;

When using the Result object, you should consume the entire result (iterate over all rows using next(), by 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 you 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 ensures that the result is closed at the end of the statement.

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

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

This gives you:


Use the following to fetch the result items from a single column. In this case, you must read the property from the node, and not from the result:

Iterator<Node> n_column = result.columnAs( "n" );
n_column.forEachRemaining( node -> nodeResult = node + ": " + node.getProperty( "name" ) );

In this case, there is only one node in the result:

Node[0]: my node

Use this only if the result contains a single column or you are 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 Neo4j Javadocs.

For more information and examples for Cypher, see Neo4j Cypher Manual.