0
votes

I have a situation where I need to check if a vertex with three satisfying properties property1='a',property2='b',property3='c' already exists in a graph and if it does not exist, I need to create it. Basically there should be a unique vertex in the graph with the combination of these three properties. I have tried out this snippet of gremlin code to check based on one property 'id'

getOrCreate = { id ->
  def p = g.V('userId', id)
  if (p.hasNext()) ? p.next() : g.addVertex([userId:id])

Not very clear about the best way to modify this to achieve what i need with gremlin since I'm a beginner. All I can think of is nesting more if's and else's in the last statement. Any help is appreciated, thank you.

2

2 Answers

2
votes

There are several approaches. One way would be to extend your traversal a bit:

getOrCreate = { one, two, three ->
  def p = g.V('prop1', one).has('prop2',two).has('prop3',three)
  p.hasNext() ? p.next() : g.addVertex([prop1:one,prop2:two,prop3:three])

In the above code, prop1 represents an indexed property, then you just filter on the rest. That prop should be the most selective property in that it should filter out the most results.

If for some reason prop is not selective enough then this solution might not be fast enough. In other words, if you have 1 billion vertices and g.V('prop1', one) returns 100000 then you will be in-memory filtering those, which will be kinda slow. If this is your case, I would consider creating a "poor-man's" composite index, by adding a fourth property to index on that combines all three properties into one. Then just do your lookups on that.

0
votes

You're almost there.

getOrCreate = { p1, p2, p3 ->
  def p = g.V().has('property1', p1).has('property2', p2).has('property3', p3)
  p.hasNext() ? p.next() : g.addVertex(['property1':p1,'property2':p2,'property3':p3])
}

Cheers, Daniel