Neo4j Cypher: How to iterate over ExecutionResult

2019-01-24 11:57发布

问题:

In this code, how could I iterate over all the nodes in the ExecutionResult result?

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

回答1:

The javadoc for Cypher isn't very clear about this, possibly because there isn't any.

So I re-created your code in a "trial" that demonstrates how to iterate over the properties of nodes in the match. The domain is kinds of fruit, where each kind is linked to the "fruit" node. The relevant snippet is this, after running the query:

    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));
        }
    }

It's the result.columnAs("x") that is the key. The cleverly named String n parameter refers to a "column name" in the result clause. In this example we want the "x" column and we expect it to contain Node objects, so we can assign straight to an Iterator<Node> and then use that.

If the column can't be found, we'll get an org.neo4j.graphdb.NotFoundException.

If we ask for assignment to the wrong class, we'll get the usual java.lang.ClassCastException.

The 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 that helps.

Cheers, Andreas



回答2:

for (Map<String,Object> row : result) {
   Node x = (Node)row.get("x");
   for (String prop : x.getPropertyKeys()) {
      System.out.println(prop +": "+x.getProperty(prop));
   }
}


回答3:

Iterator<Object> columnAs = result.columnAs("n");
while(columnAs.hasNext())
{
Node n = (Node)columnAs.next();
for (String key : n.getPropertyKeys()) {
sysout("{ " + key + " : " + n.getProperty(key)+ " } ");
}

This might help you out



回答4:

In newer versions of the java driver one can traverse like this.

Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "neo4j"));
Session session = driver.session();
List<String> teams = new ArrayList<>();

StatementResult cursor = session.run("match (l:League)<-[]-(t:Team) return t.short_name");
while (cursor.hasNext()) {
    teams.add(cursor.next().get(cursor.keys().get(0)).toString());
}

session.close();
driver.close();


标签: neo4j cypher