Search code examples
graphgremlintinkerpop

How to avoid duplicate edge between two vertices in Gremlin apache Tinker pop?


How to avoid duplicate edge between two vertices in Gremlin apache Tinker pop?

A ->(has) -> B

the edge with the same label HAS should not duplicate.


Solution

  • One simple way to ensure uniqueness is to leverage a composite ID for each edge that is comprised of the source vertex ID, the edge label, and the destination vertex ID. This would ensure that attempting to add another edge between two vertices with the same label would throw an error (as each vertex and edge in TinkerPop must have a unique ID).

    gremlin> g.addV('vertex').property(id,'v1').as('a').
    ... addV('vertex').property(id,'v2').as('b').
    ... addE('HAS').property(id,'v1-HAS-v2').from('a').to('b')
    ==>e[v1-HAS-v2][v1-HAS->v2]
    
    gremlin> g.addE('HAS').property(id,'v1-HAS-v2').from(V('v1')).to(V('v2'))
    Edge with id already exists: v1-HAS-v2
    Type ':help' or ':h' for help.
    Display stack trace? [yN]N