Neo4j Cypher:如何迭代 ExecutionResult 结果 [英] Neo4j Cypher: How to iterate over ExecutionResult result
问题描述
在这段代码中,我如何遍历 ExecutionResult 结果中的所有节点?
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
推荐答案
Cypher 的 javadoc 对此不是很清楚,可能是因为没有.
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(" " + propertyKey + " : " +
kindOfFruit.getProperty(propertyKey));
}
}
result.columnAs("x")
是关键.巧妙命名的 String n
参数指的是结果子句中的列名".在这个例子中,我们想要x"列,我们希望它包含 Node
对象,所以我们可以直接分配给 Iterator
然后使用它.
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.
如果找不到该列,我们将收到 org.neo4j.graphdb.NotFoundException
.
If the column can't be found, we'll get an org.neo4j.graphdb.NotFoundException
.
如果我们要求分配给错误的类,我们会得到通常的java.lang.ClassCastException
.
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
希望有所帮助.
干杯,安德烈亚斯
这篇关于Neo4j Cypher:如何迭代 ExecutionResult 结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!