4.9. 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 like this:

GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
// add some data first
Transaction tx = db.beginTx();
try
{
    Node refNode = db.getReferenceNode();
    refNode.setProperty( "name", "reference node" );
    tx.success();
}
finally
{
    tx.finish();
}

// let's execute a query now
ExecutionEngine engine = new ExecutionEngine( db );
ExecutionResult result = engine.execute( "start n=node(0) return n, n.name" );
System.out.println( result );

Which will output:

+----------------------------------------------------+
| n                               | n.name           |
+----------------------------------------------------+
| Node[0]{name->"reference node"} | "reference node" |
+----------------------------------------------------+
1 row, 0 ms
[Caution]Caution

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();
System.out.println( columns );

This outputs:

[n, n.name]

To fetch the result items in 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" );
    System.out.println( nodeResult );
}

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

Node[0]: reference 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";
}
System.out.println( rows );

This outputs:

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

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

For more information and examples for Cypher, see Chapter 16, Cypher Query Language and Chapter 5, Cypher Cookbook.