original:http://docs.neo4j.org/chunked/milestone/tutorials-cypher-java.html
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, keep id of node so we can refer to it
long id;
Transaction tx = db.beginTx();
try
{
Node refNode = db.createNode();
id = refNode.getId();
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(“+id+”) return n, n.name” );
Which will output:
+—————————————————+
| n | n.name |
+—————————————————+
| Node[1]{name:”reference node”} | “reference node” |
+—————————————————+
1 row
0 ms
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
This outputs:
[n, n.name]
To fetch the result items in a single column, do like this:
Iterator
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]: reference node
To get all columns, do like this instead:
for ( Map
{
for ( Entry
{
rows += column.getKey() + “: ” + column.getValue() + “; “;
}
rows += “\n”;
}
This outputs:
n.name: reference 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 15, Cypher Query Language and Chapter 7, Data Modeling Examples.