gremlintinkerpop3gremlin-java

How to add new vertex using gremlin coalesce when the traversal is empty?


I am using @GremlinDsl so my traversal from g.V().hasLabel('NEW'), so I am using coalesce to add new vertices. It works well when there is any vertex with the given LABEL in the database, otherwise, it throws an exception. It's obvious the traversal is empty from g.V().hasLabel('NEW').

g.V().hasLabel('NEW').coalesce(__.V().hasId('T12321321R'),
__.addV('NEW')
.property(T.id, 'T12321321R'))

How to solve this, when we create the given vertex(Label) for the first time in the database? Any idea?


Solution

  • You need conditional write through fold and unfold.

    gremlin> g.V()
    
    gremlin> g.V().
    ......1>   hasLabel('NEW').
    ......2>   hasId('T12321321R').
    ......3>   fold().
    ......4>   coalesce(unfold(), addV('NEW').property(T.id, 'T12321321R'))
    ==>v[T12321321R]
    
    gremlin> g.V()
    ==>v[T12321321R]
    
    gremlin> g.V().
    ......1>   hasLabel('NEW').
    ......2>   hasId('T12321321R').
    ......3>   fold().
    ......4>   coalesce(unfold(), addV('NEW').property(T.id, 'T12321321R'))
    ==>v[T12321321R]
    
    gremlin> g.V()
    ==>v[T12321321R]