0

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

user1293071
  • 253
  • 1
  • 3
  • 14

2 Answers2

2

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]
Kelvin Lawrence
  • 14,674
  • 2
  • 16
  • 38
1

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.

bechbd
  • 6,206
  • 3
  • 28
  • 47
  • Many thanks, this works. One strange issue I faced here, when I do the debug in the IDE, it is not retuning any result if I put a breakpoint in the first place, ie g.V('test') in the example. But if I do a RUN, it is working properly. Is the lazy initiation means, will it execute if the execution take time on debug? thank you in advance – user1293071 Nov 25 '20 at 19:02
  • Lazy evaluation means that until you add a terminal step, such as toList() the traversal will not execute. In the case of g.V('test') the value returned will be the GraphTraversalSource not the results of that portion of the traversal. You need to manually iterate each portion if you want to see the results of a subsection of the traversal by adding the terminal step – bechbd Nov 25 '20 at 23:00