I'm using cosmos graph db in azure.
Does anyone know if there is a way to add an edge between two vertex only if it doesn't exist (using gremlin graph query)?
I can do that when adding a vertex, but not with edges. I took the code to do so from here:
g.Inject(0).coalesce(__.V().has('id', 'idOne'), addV('User').property('id', 'idOne'))
Thanks!
It is possible to do with edges. The pattern is conceptually the same as vertices and centers around coalesce()
. Using the "modern" TinkerPop toy graph to demonstrate:
gremlin> g.V().has('person','name','vadas').as('v').
V().has('software','name','ripple').
coalesce(__.inE('created').where(outV().as('v')),
addE('created').from('v').property('weight',0.5))
==>e[13][2-created->5]
Here we add an edge between "vadas" and "ripple" but only if it doesn't exist already. the key here is the check in the first argument to coalesce()
.
UPDATE: As of TinkerPop 3.6.0, the fold()/coalesce()/unfold()
pattern has been largely [replaced by the new steps][3] of mergeV()
and mergeE()
which greatly simplify the Gremlin required to do an upsert-like operation. Under 3.6.0 and newer versions, you would write:
gremlin> g.V().has('person','name','vadas').as('v2').
......1> V().has('software','name','ripple').as('v5').
......2> mergeE([(from):outV, (to): inV, label: 'created']).
......3> option(onCreate, [weight: 0.5]).
......4> option(outV, select('v2')).
......5> option(inV, select('v5'))
==>e[13][2-edge->5]
You could also do this with id
value if you know them which makes it even easier:
gremlin> g.mergeE([(from): 2, (to): 5, label: 'created']).
......1> option(onCreate, [weight: 0.5])
==>e[13][2-edge->5]