I, too, was looking for an idempotent way to create several vertices in a single command and get the results back. (I use Cosmos DB's Gremlin API, and the typical solution using fold...coalesce...unfold doesn't work when chained together.)
Through some experimentation, I came up with this alternative whose complexity is linear as you add more vertices. I'm using inject()
to artificially create a "source" for the first invocation of coalesce()
.
g.inject("0")
.coalesce(__.V(['pk1','00']), addV('MyV')
.property('id','00')
.property('partitionKey','pk1')).as('x')
.coalesce(__.V(['pk1','01']), addV('MyV')
.property('id','01')
.property('partitionKey','pk1'))
.as('x')
.coalesce(__.V(['pk1','02']), addV('MyV')
.property('id','02')
.property('partitionKey','pk1'))
.as('x')
.select('x')
For those unconcerned about partition keys, that looks like this:
g.inject("0")
.coalesce(__.V('00'), addV('MyV').property('id','00')).as('x')
.coalesce(__.V('01'), addV('MyV').property('id','01')).as('x')
.coalesce(__.V('02'), addV('MyV').property('id','02')).as('x')
.select('x')
Additionally, we can create any number of edges between new vertices at the same time by providing unique labels (with as()
).
g.inject("0")
.coalesce(__.V(['pk2','05']), addV('MyV').property('id','05')
.property('partitionKey','pk2')
.property('ABC','123467890'))
.as('x').as('a')
.coalesce(__.V(['pk2','06']), addV('MyV').property('id','06')
.property('partitionKey','pk2')
.property('ABC','123467890'))
.as('x')
.coalesce(g.E(['pk2','07']), addE('MyE').property('id','07').from('a'))
.as('x')
.select('x')