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 ); try ( Transaction tx = db.beginTx(); ) { Node myNode = db.createNode(); myNode.setProperty( "name", "my node" ); tx.success(); }
Execute a query:
ExecutionEngine engine = new ExecutionEngine( db ); ExecutionResult result; try ( Transaction ignored = db.beginTx() ) { result = engine.execute( "start n=node(*) where n.name = 'my node' return n, n.name" );
Note | |
---|---|
Keep the |
The result will be:
+-------------------------------------+ | n | n.name | +-------------------------------------+ | Node[0]{name:"my node"} | "my node" | +-------------------------------------+ 1 row
Caution | |
---|---|
The classes used here are from the |
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[0]: 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[0];
Caution | |
---|---|
|
Caution | |
---|---|
When using an ExecutionResult, you’ll need to exhaust it by using any of the iterating methods ( |
For more information on the Java interface to Cypher, see the Java API.
For more information and examples for Cypher, see Part III, “Cypher Query Language” and Chapter 5, Data Modeling Examples.
Copyright © 2014 Neo Technology