Reputation: 410
I have graph with each node having Parent relationship with its child (as shown in attached image) and a name attribute . I want to display this graph in the from of nested json object like this:
{name: A,
children: [{name: A1,
children: A11, A12, A13 },
{name: A2,
children: A21, A22, A23},
{name: A3,
children: A31, A32, A33}
]}
I want to traverse any depth so the rlationship should be sort of (a)-[*]->(b). With reference to this question, I came up with following query:
match(parent{name: "A"})-[*]->(child)
with parent, child, collect(child.name) as children
return {name: parent.name,
children: collect({name: child.name,
children: children})}
But the above query produces following result:
name A
children [
name A23
children [A23]
,
name A22
children [A22]
,
name A32
children [A32]
,
name A2
children [A2]
,
name A12
children [A12]
,
name A21
children [A21]
,
name A31
children [A31]
,
name A1
children [A1]
,
name A11
children [A11]
,
name A33
children [A33]
,
name A3
children [A3]
,
name A13
children [A13]
]
So, what could be the possible solution to represent this full tree in the form of json object as mentioned above?
Upvotes: 1
Views: 645
Reputation: 41676
I added a function like this to APOC, feel free to check it out: https://github.com/neo4j-contrib/neo4j-apoc-procedures#fromtojson
CREATE p1=(m:Movie {title:'M'})<-[:ACTED_IN {role:'R1'}]-(:Actor {name:'A1'}),
p2 = (m)<-[:ACTED_IN {role:'R2'}]-(:Actor {name:'A2'}) WITH [p1,p2] as paths
CALL apoc.convert.toTree(paths) YIELD value RETURN value
->
{_id=0, _type=Movie, title=M,
acted_in=[
{_id=1, _type=Actor, name=A1, acted_in.role=R1},
{_id=2, _type=Actor, name=A2, acted_in.role=R2}]}
Upvotes: 3