Gremlin add edge if not exists

Viewed 160

I have the following code to insert two vertices/nodes, and an edge. It insert edge when the edge is NOT already exists.

g.V(100).hasLabel("pickup").fold().coalesce(
    unfold(),
    addV("pickup").property(T.id, 100).property("Ford", "F-150")
);

g.V(101).hasLabel("vehicle").fold().coalesce(
    unfold(),
    addV("vehicle").property(T.id, 101).property("name", "all-vehicle")
);

g.V(100).hasLabel("pickup").as('v').V(101).hasLabel("vehicle").coalesce(
    __.inE('created').where(outV().as('v')),
    addE('parent').from('v'));

However, If I run insert edge query the 2nd time

g.V(100).hasLabel("pickup").as('v').V(101).hasLabel("vehicle").coalesce(
    __.inE('created').where(outV().as('v')),
    addE('parent').from('v'));

Another edge is created. See below for visualization. You can duplicate the same problem at https://gremlify.com/.

How can I ensure only one edge is created? Even I run the insert edge query multiple times.

enter image description here

1 Answers

You are creating the edge with a parent label, but testing for it using a created label. This works:

gremlin> g.V(100).hasLabel("pickup").as('v').V(101).hasLabel("vehicle").coalesce(
......1>     __.inE('parent').where(outV().as('v')),
......2>     addE('parent').from('v'));    
==>e[5][100-parent->101]

gremlin> g.V(100).hasLabel("pickup").as('v').V(101).hasLabel("vehicle").coalesce(
......1>     __.inE('parent').where(outV().as('v')),
......2>     addE('parent').from('v'));    
==>e[5][100-parent->101]      
Related