如何在Java Neo4J中正确迭代Cypher查询的组合结果

时间:2016-12-11 11:41:45

标签: java neo4j cypher

我想执行并打印从Java调用的Cypher(Neo4J)查询的结果,但结果由多个节点类型组成 - 例如RETURN u, g。如何在结果中显示所有类型

我尝试拨打row.get("u");row.get("g");,但两者分别为NullPointerExceptiong生成u

String q = "MATCH (u:user) OPTIONAL MATCH (u)-[:OWNS]-(g:group) RETURN u, g";
Result res = DB.execute(q);
while (res.hasNext()) {
    Map<String, Object> row = res.next();
    Node n = (Node) row.get("u");
    System.out.println(n.getAllProperties());
}

我应该如何使用row.get("");来浏览不同类型的结果节点?

1 个答案:

答案 0 :(得分:1)

最后我意识到结果是返回用户及其组,这可能不存在。即:

+------+-------+
| user | group |
+------+-------+
|  u1  |   g1  |
|  u1  |   g2  |
|  u2  |  null |
|  u3  |   g3  |
+------+-------+

结果中的节点对的解决方案是:

while (res.hasNext()) {
    Map<String, Object> row = res.next();
    Node n = (Node) row.get("u");
    if (row.get("g") != null) { //that was causing the NullPointerException
        Node g = (Node) row.get("g");
        System.out.println(n.getAllProperties() + ": " + g.getAllProperties());
    } else System.out.println(n.getAllProperties());
}