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:
try ( Transaction ignored = db.beginTx(); Result result = db.execute( "match (n {name: 'my node'}) return n, n.name" ) ) { while ( result.hasNext() ) { Map<String,Object> row = result.next(); for ( Entry<String,Object> column : row.entrySet() ) { rows += column.getKey() + ": " + column.getValue() + "; "; } rows += "\n"; } }
In the above example, we also show how to iterate over the rows of the Result
.
The code will generate:
n.name: my node; n: Node[0];
Caution When using an |
Tip Using a try-with-resources statement will make sure that the result is closed at the end of the statement. This is the recommended way to handle results. |
You can also get a list of the columns in the result like this:
List<String> columns = result.columns();
This gives us:
[n, n.name]
To fetch the result items from a single column, do like below. In this case we’ll have to read the property from the node and not from the result.
Iterator<Node> n_column = result.columnAs( "n" ); for ( Node node : Iterators.asIterable( n_column ) ) { nodeResult = node + ": " + node.getProperty( "name" ); }
In this case there’s only one node in the result:
Node[0]: my node
Only use this if the result only contains a single column, or you are only interested in a single column of the result.
Note
|
For more information on the Java interface to Cypher, see the Java API.
For more information and examples for Cypher, see Cypher Query Language and Chapter 5, Basic Data Modeling Examples.