4

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 )
Dave Bennett
  • 10,996
  • 3
  • 30
  • 41
blackmamba
  • 1,952
  • 11
  • 34
  • 59

1 Answers1

4

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)))
Dave Bennett
  • 10,996
  • 3
  • 30
  • 41
  • Works like a charm. Thanks Dave :D – blackmamba Jan 26 '16 at 13:16
  • One more thing: What if I want node a in the collection too? – blackmamba Jan 26 '16 at 14:12
  • 1
    simply remove the `tail()` function from the return statement and you will receive the full list of nodes in the path. – Dave Bennett Jan 26 '16 at 14:14
  • Is it possible to filter it more? As in, if I want the path to end before the point it hits a certain label. Like : match p=(a:Node {name: 'A'})-[:CHILD_OF*]->(end:Node) where not (end:yoyo)-[:CHILD_OF]->() return tail(nodes(p)) – blackmamba Jan 26 '16 at 16:06