Austin Malpede
Austin Malpede

Reputation: 115

Adding Multiple Unique Vertices

I want to write a single gremlin query that will create multiple vertices, but only does so if they are all unique. I know I can use the get or addV method by using coalesce step mentioned in the comments.

g.V().has('com.demo.test', '__type', 'Namespace').fold().coalesce(unfold(), addV('com.demo.test').property('__type', 'Namespace'))

This will hadd a single vertex only if it does not exist already. What if i want to do this same procedure for multiple edges and vertices all in a single query? My goal is that if one of the vertices/edges is not unique, none of them are created. However I understand that may not be possible so all answers are welcome.

Thanks

Upvotes: 0

Views: 816

Answers (2)

Sam H
Sam H

Reputation: 889

I was looking for an idempotent way to create several vertices in a single command. 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 coalesce to build from.

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')

Upvotes: 0

Austin Malpede
Austin Malpede

Reputation: 115

I found a possible solution. This works but there might be a better way to do it.

g.V().coalesce(
  V().has(label,'Namespace61'),
  addV('Namespace61')).
coalesce(
  V().has(label,'Namespace76'),
  addV('Namespace76')).
coalesce(
  V().has(label,'Namespace74'),
  addV('Namespace74')
).dedup()

Upvotes: 0

Related Questions