Search code examples
gremlintinkerpop3

Why is the depth of leaf node a garbage value instead of being one?


In the recipes section of Tinkerpop/Gremlin the below command is used to compute the depth of a node. This command computes the depth of a node by counting the node itself. However, when we run this command on a leaf node, it returns a garbage value instead of 1. Could someone please clarify regarding this ?

Command:

g.V().has('name','F').repeat(__.in()).emit().path().count(local).max()

If 'F' is a leaf node then it returns incorrect value. I think it should return 1.


Solution

  • Using the same data from the maximum depth recipe, here are some of the results:

    gremlin> g.V().has('name', 'F').repeat(__.in()).emit().path().count(local).max()
    ==>5
    gremlin> g.V().has('name', 'C').repeat(__.in()).emit().path().count(local).max()
    ==>3
    gremlin> g.V().has('name', 'A').repeat(__.in()).emit().path().count(local).max()
    ==>-2147483648
    

    We can learn more about the behavior by removing the last couple steps:

    gremlin> g.V().has('name', 'C').repeat(__.in()).emit().path()
    ==>[v[4],v[6]]
    ==>[v[4],v[2]]
    ==>[v[4],v[2],v[0]]
    gremlin> g.V().has('name', 'A').repeat(__.in()).emit().path()
    gremlin>
    

    You can see that 'C' has 3 paths and 'A' has 0 paths. This is because all of the traversers were killed before anything was emitted. If you move the emit() step before the repeat() step, you will get your desired behavior:

    gremlin> g.V().has('name', 'A').emit().repeat(__.in()).path()
    ==>[v[0]]
    gremlin> g.V().has('name', 'A').emit().repeat(__.in()).path().count(local).max()
    ==>1
    

    You can read a more about the repeat() step and its interactions with the emit() step in the TinkerPop documentation. Specifically, there is a callout box that states:

    If emit() is placed after repeat(), it is evaluated on the traversers leaving the repeat-traversal. If emit() is placed before repeat(), it is evaluated on the traversers prior to entering the repeat-traversal.