Search code examples
graph-theorygremlintinkerpop3

How to know the number of vertices encountered while traversing from one vertex to another in gremlin


enter image description here

In the above picture we can see that , I can traverse to node 5 from both node 1 and 2 , but while traversing from 1 only one vertex in encountered which is 3 but for two it is 5 and 4 .

How can I write a gremlin query , that will return the number of vertex encountered .


Solution

  • When asking questions about Gremlin a picture can be helpful, but it is far more important to provide a Gremlin script that creates some sample data - like this:

    g.addV().property(id,1).as('1').
      addV().property(id,2).as('2').
      addV().property(id,3).as('3').
      addV().property(id,4).as('4').
      addV().property(id,5).as('5').
      addE('link').from('1').to('3').
      addE('link').from('2').to('3').
      addE('link').from('2').to('4').
      addE('link').from('3').to('5').
      addE('link').from('4').to('5').iterate()
    

    In answer to your question, I think you just need to use path() step to show where Gremlin has traversed:

    gremlin> g.V().repeat(out()).emit().path()
    ==>[v[1],v[3]]
    ==>[v[1],v[3],v[5]]
    ==>[v[2],v[3]]
    ==>[v[2],v[4]]
    ==>[v[2],v[3],v[5]]
    ==>[v[2],v[4],v[5]]
    ==>[v[3],v[5]]
    ==>[v[4],v[5]]
    

    If you're just interested in paths between vertices 1/2 and 5 then you can add some restrictions:

    gremlin> g.V(1,2).repeat(out()).emit(hasId(5)).path()
    ==>[v[1],v[3],v[5]]
    ==>[v[2],v[3],v[5]]
    ==>[v[2],v[4],v[5]]
    

    Building on that further, if you want to count the vertices in the middle of the path, then you could unfold() the paths, filter away your start/end vertices and count():

    gremlin> g.V(2).
    ......1>   repeat(out()).
    ......2>     emit(hasId(5)).
    ......3>   path().
    ......4>   unfold().
    ......5>   not(hasId(2,5)).
    ......6>   dedup().
    ......7>   count()
    ==>2
    

    Hopefully, that gives you some inspiration. There are a lot of nice examples of this in Gremlin Recipes.