Neo4j Cypher: how to iterate the result of an ExecutionResult

In this code, how can I iterate over all nodes as a result of executing an ExecutionResult?

CypherParser parser = new CypherParser(); ExecutionEngine engine = new ExecutionEngine( graphDb ); Query query = parser.parse( "START n=node(2) MATCH (n)<-[:IS_A]-(x) RETURN x" ); ExecutionResult result = engine.execute( query ); // iterate over nodes in result and print all properties 
+7
source share
3 answers

Javadoc for Cypher is not very clear about this, perhaps because it is not there.

So, I recreated your code in the “trial version”, which demonstrates how to iterate over the properties of nodes in a match. A domain is a kind of fruit, where each kind is associated with a “fruit” node. Corresponding fragment of this word after query execution:

  Iterator<Node> kindsOfFruit = result.columnAs("x"); while (kindsOfFruit.hasNext()) { Node kindOfFruit = kindsOfFruit.next(); System.out.println("Kind #" + kindOfFruit.getId()); for (String propertyKey : kindOfFruit.getPropertyKeys()) { System.out.println("\t" + propertyKey + " : " + kindOfFruit.getProperty(propertyKey)); } } 

This is the key result.columnAs("x") . The skillfully named String n parameter refers to the "column name" in the result clause. In this example, we need the column "x", and we expect it to contain Node objects, so we can assign it directly to Iterator<Node> , and then use this.

If the column is not found, we get an org.neo4j.graphdb.NotFoundException .

If we ask to assign the wrong class, we get a regular java.lang.ClassCastException .

A full working example is available here: https://github.com/akollegger/neo4j-trials/blob/master/src/test/java/org/akollegger/neo4j/trials/richardw/ExecutionResultIteratorTrial.java

Hope this helps.

Cheers, Andreas

+8
source
 for (Map<String,Object> row : result) { Node x = (Node)row.get("x"); for (String prop : x.getPropertyKeys()) { System.out.println(prop +": "+x.getProperty(prop)); } } 
+2
source
 Iterator<Object> columnAs = result.columnAs("n"); while(columnAs.hasNext()) { Node n = (Node)columnAs.next(); for (String key : n.getPropertyKeys()) { sysout("{ " + key + " : " + n.getProperty(key)+ " } "); } 

It can help you.

+1
source

All Articles