Search code examples
neo4jcypherpy2neo

Neo4j parent-child relationship


I have a node and I need to find all parent relationship to it till root.

So, if I have: A->B->C->D(root) A->E->F->D(root)

A is the node I have and I need all the ancestors of it.

I tried the cypher query:

MATCH (n:yo {name:"foo"})-[:HELLO*1..]->(p:yo) RETURN p

But it shows me a list like this: B,C,D,E,F. So the connection between them is lost. Is it possible to have list like [[B->C->D],[E->F->D]]

I saw this query on a website and it works. But it returns [[A,B],[A,B,C],[A,B,C,D]]. I don't need the subpaths.

start c = node:node_auto_index ( object_id = ‘10179’  )
MATCH path =  c <- [ : PARENT_OF* ] – p
return  distinct
length ( path )  AS PATH_LENGTH
, extract ( n in nodes ( path ) : n.object_id ) as the_path
order by length ( path )

Solution

  • You are looking for something like this. Match paths that start at the A node and end with a node that is not a :CHILD_OF another node. This will return two rows of node collections per your sample data:

    MATCH p=(a:Node {name: 'A'})-[:CHILD_OF*]->(end:Node)
    WHERE NOT (end)-[:CHILD_OF]->()
    RETURN tail(nodes(p))
    

    You could also collect() the result if you wanted a single row returned.

    MATCH p=(a:Node {name: 'A'})-[:CHILD_OF*]->(end:Node)
    WHERE NOT (end)-[:CHILD_OF]->()
    RETURN collect(tail(nodes(p)))