Search code examples
gremlintinkerpop3

Recursively query simpler tree-like structures with Gremlin


Consider the following data:

g.addV('RootTopic').property('name', 'A').as('A')
.addV('RootTopic').property('name', 'M').as('M')
.addV('Topic').property('name', 'A1').as('A1')
.addV('Topic').property('name', 'A2').as('A2')
.addV('Topic').property('name', 'B1').as('B1')
.addV('Topic').property('name', 'B2').as('B2')
.addV('Topic').property('name', 'N1').as('N1')
.addV('Topic').property('name', 'N2').as('N2')
.addV('Topic').property('name', 'O1').as('O1')
.addE('refines').from('A').to('A1')
.addE('refines').from('A').to('A2')
.addE('refines').from('A1').to('B1')
.addE('refines').from('A1').to('B2')
.addE('refines').from('M').to('N1')
.addE('refines').from('M').to('N2')
.addE('refines').from('N2').to('O1')
.addE('refines').from('N2').to('O2')

What I would like is something that one gets by using the tree()-step:

g.V().hasLabel('RootTopic').repeat(out()).times(2).emit().tree()

However, this pulls out the full vertex. What I really just need in this situation are properties of the vertex, e.g. the name, such that we get a tree that contains e.g. just the name-property of the Vertex.

I know that if I write .tree().by('name') I seem to get a tree with the name as key, but I am trying to find a way which would allow me to select e.g. multiple properties of a Vertex, or e.g. just a certain property having some specific meta-property.

Is this possible?


Solution

  • The by() modulator can take more than just a property key value as an argument. You can also pass in an anonymous traversal which would thus allow:

    g.V().hasLabel('RootTopic').
      repeat(out()).times(2).
        emit().
      tree()
        by(values('name','k1','k2').fold())
    

    or you might use project() if you had more complex output:

    g.V().hasLabel('RootTopic').
      repeat(out()).times(2).
        emit().
      tree()
        by(project('name','k1','degree').
             by('name').
             by('k1').
             by(both().count())
    

    The main point to take away here is that with an anonymous traversal you can develop just about any output you would like.