Gremlin optional as empty

615 views Asked by At

Could you please help me to understand whether there is any option where we can skip the optional in the gremlin,

the scenario is, we are traversing through a graph and has an optional statement

depending on a query parameter in the request, I will be having a traverse path for optional, if not, there is no path for the optional

for example,

if query_parameter:
 path=has('labeltest').inE().outV()

g.V('test').optional(path)

as optional path is for the query_parameter available condition, this is failing and returning no result if query parameter not available. We don't prefer to repeat the code on the g.v() by an if and else condition. Any thoughts to tell the optional to not do anything or dummy options to return the previous path. Appreciate your thoughts as I am new to this, thank you in advance

Regards Hari

2

There are 2 answers

2
bechbd On BEST ANSWER

If you are doing this from python using the Gremlin Language Variant (GLV) then you can only add the optional portion of the query when needed. GLV's are lazily evaluated so you can conditionally construct them in code. They will only be executed when you add a terminal step (e.g. toList()). This means that you can build your traversal like this:

t=g.V('test')
if query_parameter:
  t=t.has('labeltest').inE().outV()
res=t.toList()

With this code, the optional path portion of the traversal will only be executed when query_parameter is True, else it will just return the test vertex.

0
Kelvin Lawrence On

In the case where you want nothing to happen you could just set your path variable to be identity(). The effect would be as follows:

gremlin> g.V('3').optional(identity())
==>v[3]

Specifically, in Python you can do this:

>>> p=__.identity()
>>> g.V('3').optional(p).next()
v[3]