8

在这段代码中,我如何遍历 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
4

4 回答 4

9

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对象,所以我们可以直接分配给 anIterator<Node>然后使用它。

如果找不到该列,我们将得到一个org.neo4j.graphdb.NotFoundException.

如果我们要求分配到错误的班级,我们会得到通常的java.lang.ClassCastException.

完整的工作示例可在此处获得: https ://github.com/akollegger/neo4j-trials/blob/master/src/test/java/org/akollegger/neo4j/trials/richardw/ExecutionResultIteratorTrial.java

希望有帮助。

干杯,安德烈亚斯

于 2011-12-29T15:57:28.753 回答
3
for (Map<String,Object> row : result) {
   Node x = (Node)row.get("x");
   for (String prop : x.getPropertyKeys()) {
      System.out.println(prop +": "+x.getProperty(prop));
   }
}
于 2012-02-04T23:58:41.430 回答
2
Iterator<Object> columnAs = result.columnAs("n");
while(columnAs.hasNext())
{
Node n = (Node)columnAs.next();
for (String key : n.getPropertyKeys()) {
sysout("{ " + key + " : " + n.getProperty(key)+ " } ");
}

这可能会帮助你

于 2012-08-28T12:59:36.553 回答
1

在较新版本的 java 驱动程序中,可以像这样遍历。

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();
于 2018-03-29T08:44:25.680 回答