Search code examples
groovygremlintinkerpoptinkerpop3

Why can't a Gremlin GraphTraversal be captured as a Groovy variable?


I am experimenting with the traversal examples from the TinkerPop3 documentation. Having loaded up the classic graph with g = TinkerFactory.createClassic(), at the Gremlin shell:

gremlin> marko = g.v(1)
==>v[1]
gremlin> marko
==>v[1]

However:

gremlin> marko = g.V().has('name', 'marko')
==>v[1]
gremlin> marko
gremlin>

Why does the second form not capture v[1]?


Given the second form, attemping to use the variable results in an error:

gremlin> marko.out('knows')
The traversal strategies are complete and the traversal can no longer have steps added to it
Display stack trace? [yN] 

Solution

  • You're dealing with different class types from each of those results. Consider my console session below:

    gremlin> g = TinkerFactory.createClassic()
    ==>tinkergraph[vertices:6 edges:6]
    gremlin> marko = g.v(1)
    ==>v[1]
    gremlin> marko.class
    ==>class com.tinkerpop.gremlin.tinkergraph.structure.TinkerVertex
    

    The above yields a Vertex but as you can see below:

    gremlin> marko = g.V().has('name','marko')
    ==>v[1]
    gremlin> marko.class
    ==>class com.tinkerpop.gremlin.tinkergraph.process.graph.TinkerGraphTraversal
    

    you get a Traversal instance. You see output to the console of v[1] because the console has automatically iterated the result for you. Since you have iterated it, marko becomes empty:

    gremlin> marko.hasNext()
    ==>false
    

    If you want to manually iterate then do this:

    gremlin> marko = g.V().has('name','marko');null
    ==>null
    gremlin> marko.hasNext()
    ==>true
    gremlin> marko
    ==>v[1]