0

I have an upsert query to insert vertices in the graph like this:

V().coalesce(
    __.V().hasLabel("Person").has(id, "ABC"), 
    __.addV(_a).property(id, "ABC")
).limit(1)

However, it doesn't work when the graph has 0 vertices to start with.

How can I adjust this query so that it will succeed when the graph is empty?

Chris Johnson
  • 1,230
  • 7
  • 15

2 Answers2

1

You can do this using the element existence pattern shown in the Gremlin recipes. In your example it would be:

g.V().hasLabel("Person").has(id, "ABC").fold().coalesce(
    unfold()
    addV(_a).property(id, "ABC")
).limit(1)

The fold will ensure that there is at least one traverser.

bechbd
  • 6,206
  • 3
  • 28
  • 47
  • wonderful thanks! i'm completely new to gremlin and learning the query language is a little mind bending. thanks for your help! – Chris Johnson Sep 25 '20 at 01:30
0

There is a recipe, commonly recommended for this that uses the following formulation:

g.V().hasLabel("Person").has(id,"ABC").
      fold().
      coalesce(
        unfold(),
        addV("Person").property(id, "ABC"))

Given ID's are unique you can also just do:

g.V().has(id,"ABC").
      fold().
      coalesce(
        unfold(),
        addV("Person").property(id, "ABC"))
Kelvin Lawrence
  • 14,674
  • 2
  • 16
  • 38