Search code examples
gremlintinkerpopgremlinpython

Gremlin-python: How to use user-defined-steps to reuse traversal logic


I am trying to simplify the following traversal:

operation_dict['output_schema'] = g.V(operation_id).outE('uses').inV()\
.project('id','label','attribute_id', 'attribute_name', 'dataType')\
.by(T.id).by(T.label).by('attribute_id').by('attribute_name').by('dataType').toList()

Since i would like to reuse the projection traversal, i would like to extract it from the traversal, like the following snippet:

def extract_attribute(x):
  return g.V(x).project('id','label','attribute_id', 'attribute_name', 'dataType')\
  .by(T.id).by(T.label).by('attribute_id').by('attribute_name').by('dataType')


operation_dict['input_schema'] = g.V(operation_id).inE('follows').outV().outE('uses').inV()\
    .map(lambda x: extract_attribute(x)).toList()

How can I do that in Gremlin for Python? I tried the Lambda functionality, but without success so far.


Solution

  • There are a few ways you could do this, but here's a way in line with what you were trying to do:

    >>> def c(x):
    ...     return __.project('x').by(x)
    ... 
    >>> g.V().map(c('name')).toList()
    [{'x': 'marko'}, {'x': 'vadas'}, {'x': 'lop'}, {'x': 'josh'}, {'x': 'ripple'}, {'x': 'peter'}]
    

    You just need to generate a anonymous child traversal in your extract_attribute() function. Another more advanced way to re-use traversal logic is to build a custom Gremlin DSL.