user1187968
user1187968

Reputation: 8026

Neo4j get all parents and grand parents

I have an unknown-level tree hierarchy stored in the Neo4j graph database. How can I retrieve all parents and grand parents for a given nodes. So in the following example, node "a" has parent and grand parent "c", "e", and "b"

CREATE (a {id:1})
CREATE (b {id:2})
CREATE (c {id:3})
CREATE (d {id:4})
CREATE (e {id:5})

MATCH (a), (c) WHERE a.id = 1 AND c.id = 3 CREATE (a) -[r:PARENT]-> (c)
MATCH (c), (e) WHERE c.id = 3 AND e.id = 5 CREATE (c) -[r:PARENT]-> (e)
MATCH (a), (b) WHERE a.id = 1 AND b.id = 2 CREATE (a) -[r:PARENT]-> (b)

Upvotes: 1

Views: 957

Answers (1)

Rajendra Kadam
Rajendra Kadam

Reputation: 4052

If you need parents and grandparents in one list then you can use:

MATCH (a) WHERE a.id = 1  
WITH a 
OPTIONAL MATCH (a)-[:PARENT*1..2]->(pg)  
RETURN a, collect(pg) as parents

In case you need parents in one and grandparents in another list:

MATCH (a) WHERE a.id = 1   
WITH a  
OPTIONAL MATCH (a)-[:PARENT]->(p)   
OPTIONAL MATCH (p)-[:PARENT]->(gp)   
RETURN a, collect(p) as parents, collect(gp) as grandparents

WITH is used to pass the matched node to the following sub-queries.

OPTIONAL MATCH is used so that the query returns results even if parents or grandparents nodes are not available for any node.

Suggestion: consider using labels for nodes e.g. Person

Upvotes: 3

Related Questions