Cypher - 将图形结果转换为列表或JSON

时间:2018-01-08 13:51:27

标签: json neo4j cypher py2neo

我有以下Neo4j图表结果。

Neo4j graph result
 一世 使用多关系-[RELATED_TO*]-命令来获取它。

Match(n:Comment)
MATCH(n)-[RELATED_TO*]-(d:Comment)
return n, d;

我想在List中显示结果,我可以说这个答案来自该答案,或者是JSON级联文件。达到这个目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:6)

我认为您可以使用APOC过程apoc.convert.toTree返回JSON级联结构。看看这个例子:

创建样本数据集:

CREATE (:Comment {id : 1})<-[:RELATED_TO]-(:Comment {id : 2})<-[:RELATED_TO]-(:Comment {id : 3})<-[:RELATED_TO]-(:Comment {id : 4})

查询:

MATCH p = (n:Comment)<-[RELATED_TO*]-(d:Comment)
// I believe you are interested only in the "complete" path.
// That is: you are not interested in the sub path like (:Comment {id : 2})-[:RELATED_TO]->(:Comment {id : 3}).
// So this WHERE clause is used to avoid these sub paths.
WHERE NOT (n)-->() AND NOT (d)<--()
CALL apoc.convert.toTree([p]) yield value
RETURN value

输出:

{
  "_type": "Comment",
  "related_to": [
    {
      "_type": "Comment",
      "related_to": [
        {
          "_type": "Comment",
          "related_to": [
            {
              "_type": "Comment",
              "_id": 142701,
              "id": 4
            }
          ],
          "_id": 142700,
          "id": 3
        }
      ],
      "_id": 142699,
      "id": 2
    }
  ],
  "_id": 142698,
  "id": 1
}

或者,您可以使用nodes()函数返回节点列表,并将路径作为参数传递:

MATCH p = (n:Comment)<-[RELATED_TO*]-(d:Comment)
WHERE NOT (n)-->() AND NOT (d)<--()
return nodes(p)

结果将是:

╒═════════════════════════════════════╕
│"nodes(p)"                           │
╞═════════════════════════════════════╡
│[{"id":1},{"id":2},{"id":3},{"id":4}]│
└─────────────────────────────────────┘