在这段代码中,我如何遍历 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
最佳答案
Cypher 的 javadoc 对此不是很清楚,可能是因为没有。
因此,我在“试验”中重新创建了您的代码,该代码演示了如何迭代匹配中节点的属性。域是水果的种类,其中每一种都链接到“水果”节点。运行查询后,相关代码段是这样的:
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));
}
}
这是
result.columnAs("x")
这是关键。巧妙命名String n
参数指的是结果子句中的“列名”。在这个例子中,我们想要“x”列,我们希望它包含 Node
对象,所以我们可以直接分配给 Iterator<Node>
然后使用它。如果找不到该列,我们将收到
org.neo4j.graphdb.NotFoundException
.如果我们要求分配到错误的类(class),我们会得到通常的
java.lang.ClassCastException
.完整的工作示例可在此处获得:
https://github.com/akollegger/neo4j-trials/blob/master/src/test/java/org/akollegger/neo4j/trials/richardw/ExecutionResultIteratorTrial.java
希望有帮助。
干杯,
安德烈亚斯
关于Neo4j 密码 : How to iterate over ExecutionResult result,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8650948/