pythonlambdatinkerpop3gremlinpython

How to use the lambda function in GremlinPython?


How to use the lambda function in GremlinPython?

To do a case-insensitive search, I tried the following code,

g.V().filter(lambda: "x -> x.get().value('title') == 'open', 'gremlin-groovy'").toList()

but, got the following error,

E             File "<string>", line 1
E               lambda x -> x.get().value('title') == 'open', 'gremlin-groovy'
E                         ^
E 

      SyntaxError: invalid syntax

Solution

  • Using a Gremlin Server with an empty TinkerGraph, I was able to get it to work. However, I was not initially able to get it to work when gremlin-groovy was explicitly specified. See the "UPDATED" section for an explanation of that issue.

    >>> g.addV('test').property('p','Hello').next()
    v[4]
    >>> g.V().map(lambda: 'x->x.get().values("p")[0]=="hello"').next()
    False
    >>> g.V().map(lambda: 'x->x.get().values("p")[0]=="Hello"').next()
    True
    

    or, using value instead of values

    >>> g.V().map(lambda: 'x->x.get().value("p")=="hello"').next()
    False
    >>> g.V().map(lambda: 'x->x.get().value("p")=="Hello"').next()
    True
    

    and ignoring case

    >>> g.V().map(lambda: 'x->x.get().value("p").toUpperCase()=="HELLO"').next()
    True
    

    A couple of points to note:

    1. The "lambda" uses the Groovy syntax to I had to use toUpperCase rather than the Python upper.
    2. In general it is recommended to avoid using lambdas/closures as they are not supported by all TinkerPop enabled databases.

    UPDATED

    To get the lambda to work, with the gremlin-groovy present, requires that an extra pair of parenthesis be used. This is essentially creating a tuple of the lambda and the script language hint.

    >>> g.V().map(lambda: ('x->x.get().value("p").toUpperCase()=="HELLO"','gremlin-groovy')).next()
    True