Search code examples
arangodbarangojs

How to get the root node's key of a graph in ArangoDB?


I have a graph in ArangoDB whose root node is 'X'. Now "a,b,c,d,e,f" are the siblings of 'X' direct or grand grand siblings. Now from a given siblings node "a,b,c,d,e or f" I want to get to node 'X'. Is there any general AQL query to traverse directly to the root node of any graph ?


Solution

  • To provide an exact example I would need to know a bit more, but this is one of several solutions.

    Assuming that the nodes are connected by "child" edges and the direction of the edges go from parent to child. You would traverse the tree up or INBOUND

    FOR v,e,p IN 1..50 INBOUND '(id of starting node a,b,etc.)' child RETURN p.vertices
    

    If you know how many hops maximum to the root, change the 50 to that value.

    This statement will return all of the paths and intermediate paths from the starting node through the child links to the head node. To return only the path to the head node, you would have to filter out the intermediate paths. This could be done with a check to see that there is no parent vertex.

    FOR v,e,p IN 1..50 INBOUND '(id of starting node a,b,etc.)' child 
      FILTER LENGTH(EDGES(child,v._id,'inbound'))==0 RETURN p.vertices
    

    which will filter out all paths that do not end at a root vertex.