我目前正在使用console.neo4j.org上的示例数据编写一个输出分层JSON的查询.
使用创建示例数据
create (Neo:Crew {name:'Neo'}), (Morpheus:Crew {name: 'Morpheus'}), (Trinity:Crew {name: 'Trinity'}), (Cypher:Crew:Matrix {name: 'Cypher'}), (Smith:Matrix {name: 'Agent Smith'}), (Architect:Matrix {name:'The Architect'}), (Neo)-[:KNOWS]->(Morpheus), (Neo)-[:LOVES]->(Trinity), (Morpheus)-[:KNOWS]->(Trinity), (Morpheus)-[:KNOWS]->(Cypher), (Cypher)-[:KNOWS]->(Smith), (Smith)-[:CODED_BY]->(Architect)
理想的输出如下
name:"Neo" children: [ { name: "Morpheus", children: [ {name: "Trinity", children: []} {name: "Cypher", children: [ {name: "Agent Smith", children: []} ]} ] } ] }
现在,我正在使用以下查询
MATCH p =(:Crew { name: "Neo" })-[q:KNOWS*0..]-m RETURN extract(n IN nodes(p)| n)
得到这个
[(0:Crew {name:"Neo"})] [(0:Crew {name:"Neo"}), (1:Crew {name:"Morpheus"})] [(0:Crew {name:"Neo"}), (1:Crew {name:"Morpheus"}), (2:Crew {name:"Trinity"})] [(0:Crew {name:"Neo"}), (1:Crew {name:"Morpheus"}), (3:Crew:Matrix {name:"Cypher"})] [(0:Crew {name:"Neo"}), (1:Crew {name:"Morpheus"}), (3:Crew:Matrix {name:"Cypher"}), (4:Matrix {name:"Agent Smith"})]
有任何提示来解决这个问题吗?谢谢
在neo4j 3.x中,在neo4j服务器上安装APOC插件后,可以调用该apoc.convert.toTree
过程来生成类似的结果.
例如:
MATCH p=(n:Crew {name:'Neo'})-[:KNOWS*]->(m) WITH COLLECT(p) AS ps CALL apoc.convert.toTree(ps) yield value RETURN value;
...将返回如下所示的结果行:
{ "_id": 127, "_type": "Crew", "name": "Neo", "knows": [ { "_id": 128, "_type": "Crew", "name": "Morpheus", "knows": [ { "_id": 129, "_type": "Crew", "name": "Trinity" }, { "_id": 130, "_type": "Crew:Matrix", "name": "Cypher", "knows": [ { "_id": 131, "_type": "Matrix", "name": "Agent Smith" } ] } ] } ] }