4.11. 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 );
Transaction tx = db.beginTx();
try
{
    Node myNode = db.createNode();
    myNode.setProperty( "name", "my node" );
    tx.success();
}
finally
{
    tx.finish();
}

Execute a query:

ExecutionEngine engine = new ExecutionEngine( db );
ExecutionResult result = engine.execute( "start n=node(*) where n.name! = 'my node' return n, n.name" );
[Note]Note

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

The result will be:

+-------------------------------------+
| n                       | n.name    |
+-------------------------------------+
| Node[1]{name:"my node"} | "my 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();

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[1]: 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[1];

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

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