Hi guys, I need help with query to fetch the root nodes and its levels (from the root node)
Data Structure Format
Here each nodes are connected with [:HAS_CHILD] releationship. Each of the nodes have a property uniq_id
which is used to relate them together
So I am trying to find the root nodes here. The query I am using is
MATCH (w:Node{uniq_id: <some_uniq_id>})
WHERE NOT (w)<-[:HAS_CHILD]-()
WITH COLLECT(w) AS roots
UNWIND roots as root
Return root as RootNodes, 0 as Level
Then using the root node to traverse the graph to gets its child levels
MATCH (w:Node {uniq_id: <uniq_id>)
WHERE NOT (w)<-[:HAS_CHILD]-()
WITH COLLECT(w) AS roots
UNWIND roots AS root
MATCH path=(root)-[:HAS_CHILD*]->(child)
WITH root, COLLECT(DISTINCT child) AS descendants, path
RETURN DISTINCT descendants, REDUCE(s = 0, r IN RELATIONSHIPS(path) | s + 1) AS level
But here both P1 and C3 are getting considered as the root nodes, but the use case is to get P1 as the root node and define its level 0, and then come down each depth and set a level to all the nodes (directly/indirectly)
So something like
p1 - level 0
c1,c2,c3 - level 1
gc - level 2
Note: There can be multiple valid root nodes as long as they are at the top level (level=0)
Not sure if there is any apoc function that can help with my use case here. Also, is there a better way to query my use case here.
Any help would be appreciated