Using gremlin-javascript, I'd like to perform an "add if doesn't exist" transaction like:
g.V()
.hasLabel('account').has('uid', '1')
.fold()
.coalesce(
g.V().unfold(),
g.V().addV('account').property('uid', '1')
)
How would I phrase this sort of query?
I assume that you've seen this pattern elsewhere, perhaps demonstrated in the Gremlin Console. While that's Gremlin Groovy, Gremlin is Gremlin is Gremlin, irrespective of your programming language. Aside from a few minor idiomatic differences most variants of Gremlin are identical to one another. For Javascript and this particular bit of Gremlin you are asking about the Gremlin is no different from Groovy:
g.V().
hasLabel('account').has('uid', '1').
fold().
coalesce(unfold(),
addV('account').property('uid', '1'))
Note that unfold()
or addV()
are called in an anonymous fashion. They need to just be imported from __
as discussed here.
UPDATE: As of TinkerPop 3.6.0, the fold()/coalesce()/unfold()
pattern has been largely replaced by the new steps 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:
g.mergeV(['uid':'1',(T.label): 'account'])