I'm trying to understand how this pattern for a conditional insert works:
g.V()
.hasLabel('person').has('name', 'John')
.fold()
.coalesce(
__.unfold(),
g.addV('person').property('name', 'John')
).next();
What is the purpose of the fold/unfold? Why are these necessary, and why does this not work:
g.V()
.coalesce(
__.hasLabel('person').has('name', 'John'),
g.addV('person').property('name', 'John')
).next();
The fold-then-unfold pattern seems redundant to me and yet the above does not yield the same result.
Consider what happens when you just do the following:
For "marko" you return something and for "stephen" you do not. The "stephen" case is the one to pay attention to because that is the one where the
fold()
truly becomes important in this pattern. When that traversal returns nothing, any steps you add after that will not have aTraverser
present to trigger actions in those steps. Therefore even the following will not add a vertex:But looks what happens if we
fold()
:fold()
is a reducing barrier step and will thus eagerly evaluate the traversal up to that point and return the contents as aList
even if the contents of that traversal up to that point yield nothing (in which case, as you can see, you get an empty list). And if you have an emptyList
that emptyList
is aTraverser
flowing through the traversal and therefore future steps will fire:So that explains why we
fold()
because we are checking for existence of "John" in your example and if he's found then he will exist in theList
and when thatList
with "John" hitscoalesce()
its first check will be tounfold()
thatList
with "John" and return thatVertex
- done. If theList
is empty and returns nothing because "John" does not exist then it will add the vertex (by the way, you don't need the "g." in front ofaddV()
, it should just be an anonymous traversal and thus__.addV('person')
).Turning to your example, I would first point out that I think you wanted to ask about this:
This is a completely different query. In this traversal, you're saying iterate all the vertices and for each one execute what is in the
coalesce()
. You can see this fairly plainly by replacing theaddV()
withconstant('x')
:Now, imagine what happens with
addV()
and "John". It will calladdV()
6 times, once for each vertex it comes across that is not "John":Personally, I like the idea of wrapping up this kind of logic in a Gremlin DSL - there is a good example of doing so here.
Nice question - I've described the "Element Existence" issue as part of a Gremlin Recipe that can be read here.