Using Cypher to Return Nested Hierarchical JSON from a Tree

I am currently using the sample data on console.neo4j.org to write a query that displays hierarchical JSON.

Sample data is created using

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) 

The ideal way out is as follows

 name:"Neo" children: [ { name: "Morpheus", children: [ {name: "Trinity", children: []} {name: "Cypher", children: [ {name: "Agent Smith", children: []} ]} ] } ] } 

I am using the following query now

 MATCH p =(:Crew { name: "Neo" })-[q:KNOWS*0..]-m RETURN extract(n IN nodes(p)| n) 

and getting it

 [(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"})] 

Any tips to figure this out? Thanks

+7
neo4j cypher
source share
1 answer

In neo4j 3.x, after installing the APOC plugin on the neo4j server, you can call apoc.convert.toTree to create similar results.

For example:

 MATCH p=(n:Crew {name:'Neo'})-[:KNOWS*]->(m) WITH COLLECT(p) AS ps CALL apoc.convert.toTree(ps) yield value RETURN value; 

... will return a string of results that looks like this:

  { "_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" } ] } ] } ] } 
+6
source share

All Articles