0
votes

I have a hierarchical org structure like this:

OrgNode(3)-[HAS_PARENT]->OrgNode(2)-[HAS_PARENT]->OrgNode(1)

I want a cypher query that gives me the top org given any of the node ids:

topOrg(3) = OrgNode(1)
topOrg(2) = OrgNode(1)
topOrg(1) = OrgNode(1)

I'm able to write the query to return the top org when the starting node has at least one parent. But I cannot figure out how to return starting node when there is no parent link in the same query:

start n=node(3)
match (n)-[:PARENT*]->(m)-[r?:PARENT]->()
WHERE r is null
return m
1

1 Answers

1
votes

You might use the UNION operator to combine your result with the result of another query that handles a starting node without a parent,

start n=node(3)
match (n)-[:PARENT*]->(m)-[r?:PARENT]->()
WHERE r is null
return m as result
UNION 
Start n=node(3)
Match n 
Where not(n-[:PARENT]-())
Return n as result