Search code examples
gremlinamazon-neptunegremlinpython

Gremlin Python: How to use coalesce to get vertex if exists, else insert


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?


Solution

  • 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