Search code examples
gremlinazure-cosmosdb-gremlinapi

UPSERT an edge with properties with Gremlin


I'm trying to upsert an edge (insert if it does not exist but update if it does) with properties in Gremlin via a single query.

I have this which adds a manages edge with a duration property between two vertices with id of Amy and John.

g.E().where(outV().has('id','Amy')).where(inV().has('id','John')).fold().coalesce(unfold(),g.V('Amy').as('a').V('John').addE('manages').from('a').property('duration','1year')).

The query does do an upsert, but if I change the value of the duration property, remove the duration property, or add other properties, the property changes are not reflected on the edge.

I want to be able to change the value of the duration property without adding a new edge or having to remove the old one.

I'm fairly new to Gremlin so please share any advice which may help.

I'm not sure it matters but the underlying DB is an Azure Cosmos DB.


Solution

  • Two additions to Kevin's answer:

    1. I think you need to specify the edge label in outE, otherwise the unfold may return other relationships present between the two vertices, and these will be updated with the property, rather than triggering the addE of the new edge. Specifying the edge label should ensure the length of the folded array is 0 in the case of INSERT and 1 in the case of UPDATE.

    2. For Cosmos DB Gremlin API, use the anonymous class __ when not using g

    g.V('Amy').
      outE('manages').where(inV().hasId('John')).
      fold().
      coalesce(
        unfold(),
        __.addE('manages').from(__.V('Amy')).to(__.V('John'))).
      property('duration', '1year')
    

    More detailed example here.