0

Is it possible to use the Gremlin coalesce step to select a vertex by id (or properties) if such a vertex exists, otherwise insert the vertex? I've attempted to do so with the following, but I get a 'list' object has no attribute 'coalesce' error, which I can see is caused by .fold().next() returning a python list object:

    my_vertex = g.V(1).fold().next().coalesce(__.unfold(), g.addV(
         'my_label'
        ).property(
            T.id,
            1
        ).property(
            'test', 'foo'
        ).property(
            'name', 'my_vertex_name'
        ).property(
            'created_timestamp', 1575480467
        ).next()
    )

Is there any performance benefit to doing it this way, or should I simply break this into an if/else on the hasNext() of the initial vertex query?

JTW
  • 3,546
  • 8
  • 35
  • 49

2 Answers2

3

You need to remove the next from the query. Next is a terminal step. Without the next the query should work the way you expect, if V(1) exists it will not create it otherwise it will. Other than that this is a good way to do an upsert query.

If you are using Neptune remember IDs are strings so it would be V('1').

Kelvin Lawrence
  • 14,674
  • 2
  • 16
  • 38
  • To be clear, I'm not trying to perform an upsert, rather I'm trying to perform a "get if exists, else insert". – JTW Dec 12 '19 at 21:37
  • 1
    Understood. BTW When I said remove I should have said move to the end. next() is a terminal step just like toList() and iterate() that causes the traversal to execute. – Kelvin Lawrence Dec 12 '19 at 22:24
-1

I was able to accomplish the "get if exists, else insert" by moving the next() terminal step to the end of the traversal as shown below:

my_vertex = g.V(1).fold().next().coalesce(__.unfold(), g.addV(
         'my_label'
        ).property(
            T.id,
            1
        ).property(
            'test', 'foo'
        ).property(
            'name', 'my_vertex_name'
        ).property(
            'created_timestamp', 1575480467
        )
    ).next() //notice that .next was simply moved to the close of the .coalesce step
JTW
  • 3,546
  • 8
  • 35
  • 49