0

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

Austin Malpede
  • 115
  • 2
  • 8

2 Answers2

0

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()
Dominus
  • 808
  • 11
  • 25
Austin Malpede
  • 115
  • 2
  • 8
  • That looks fine. It's the same approach used in this post https://groups.google.com/d/msg/janusgraph-dev/KfCjSbwzh9E/LBVgIzo4BgAJ – Jason Plurad Aug 07 '18 at 18:09
  • Do not do this! It looks innocent enough, but `g.V()` is a problem. This will read every vertex in the database and then try to add a new vertex for each existing one. It's too bad you can't just start with `g.coalesce(...)`. – Gyromite May 26 '23 at 22:50
0

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')
Gyromite
  • 769
  • 6
  • 16