Search code examples
treeorientdb

Most efficient way to get all predecessors with OrientDB


I have a "classical" tree structure, modelled in OrientDB.

  • One root Node, ROOT
  • several nodes with ROOT as parent, A, B, C, ... These nodes have an outgoing relationship (with label "hasParent") to ROOT
  • Sub nodes A1, A1, B1, ... all with an outgoing relationship (with label "hasParent") to A, B, ...

What i want is to query (in ONE query) a specific node at level 2 and get all predecessors in the most efficient way

I have something like:

> traverse out('hasParent') from (select from category where code='B2')

Is this the most efficient way to do it?


Solution

  • this query is quite efficient ( O(logN) where N is the number of nodes in "category" class) if you have an index defined on category.code

    Anyway, if you know the RID of B2 (suppose it's #10:1) you can write an even faster query like this:

    traverse out('hasParent') from #10:1
    

    this query has a cost of O(1) (constant time, does not depend on the size of your graph, but only on the size of the result set)

    All this of course if you know that ROOT does not have a parent, but if it's not true and you want to limit traversal depth you can write a "while" condition on the traverse, like this

    traverse out('hasParent') from #10:1 while $depth < 3