gremlinamazon-neptune

Gremin mergeV() Upsert: knowing whether the vertex was added or not(side-effect free)


In CosmosDB Graph : "upsert" query pattern, there was an awesome discussion of using fold()/coalesce()/unfold() style pattern for upserting vertex, and knowing whether the vertex has been added or obtained:

g.V().has('event','id','1').
  fold().
  coalesce(unfold().
           project('vertex','exists').
             by(identity()).
             by(constant(true)),
           addV('event').property('id','1').
           project('vertex','exists').
             by(identity()).
             by(constant(false)))

The post also made the update that there was a more advanced pattern using mergeV(). I wonder if we can "translate" the above to the more advanced mergeV() pattern?

Any help/insight is much appreciated!

The new mergeV() pattern seems to expect a list as the inputs, so i am not sure how to map that from the original queries.


Solution

  • You can use onMatch and onCreate to know what happened during the mergeV search. Here is one way to build on that to generate a result similar to the one described in the question.

    g.mergeV([T.id:'1']).
        option(Merge.onMatch,sideEffect(constant(true).store('found')).constant([:])).
        option(Merge.onCreate,sideEffect(constant(false).store('found')).constant([:])).
      project('id','status').
        by(id()).
        by(select('found').unfold())
    

    As the vertex with an ID of '1' does exist, when run, this is what the query returns:

    {'id': '1', 'status': True}
    

    Strictly speaking in this case you don't need the sideEffect wrapper, but I find it cleaner as it isolates that work from the rest of the onMatch steps.