How to get all childs of a particular node in neo4j

Viewed 4740

I have this relationship in my neo4j:

Parent -> Childs
F -> D,E
D -> A,B,C

Use case: I am trying to get all child of a particular node using this query

MATCH (p:Person{name:"F"})<-[:REPORTS_TO*]-(c) 
RETURN {parent : p.name, child : {name :collect( c.name)}}

This returns me this :

{"parent":"F","child":{"name":["D","A","B","C","E"]}}

A, B, C are not direct child of F as they are child of D

Required response is

[
"F" : [ Childs i.e "E", "D" ]
"E" : []
"D" : [ "A", "B", "C" ]
 and so on ....
]

One way to achieve this is fire this below query recursively :

MATCH (p:Person{name:"F"})<-[:REPORTS_TO]-(c) 
RETURN {parent : p.name, child : {name :collect( c.name)}}

Which returns

{"parent":"F","child":{"name":["E","D"]}}

Then search for all childs of E and D and then childs of childs and so on..

My question is can I achieve this in a single query or in a more better way?

Edit1 : Adding dataset

CREATE (f:Person {name: "F"})
CREATE (e:Person {name: "E"})
CREATE (d:Person {name: "D"})
CREATE (c:Person {name: "C"})
CREATE (b:Person {name: "B"})
CREATE (a:Person {name: "A"})
CREATE (x:Person {name: "X"})
CREATE (a)-[:REPORTS_TO]->(x)
CREATE (d)-[:REPORTS_TO]->(a)
CREATE (d)-[:REPORTS_TO]->(b)
CREATE (d)-[:REPORTS_TO]->(c)
CREATE (f)-[:REPORTS_TO]->(d)
CREATE (f)-[:REPORTS_TO]->(e)
2 Answers
Related