Search code examples
gremlingraph-databasesamazon-neptune

Gremlin - how to ensure one vertex only have one inbound edge?


I have person vertex and book vertex connected by owns edge (aka person=> owns => book). How can I ensure one book can only be owned by one person? In other words, I need a Gremlin query like addE('owns').from(person_1).to(book_1) only if the vertex book_1 has no inbound edge.


Solution

  • This pattern is described in the "Element Existence" recipe and follows the standard fold()/coalesce()/unfold() pattern. Basically, you would so something like:

    g.V('book_1_id').as('book_1').
      V('person_1_id').as('person_1').
      coalesce(outE('owns').where(outV().as('book_1')),
               addE('owns').from(`person_1`).to(`book_1`))
    

    If you are using TinkerPop 3.6.x or later you might try using the mergeE() step:

    g.mergeE([(from):'book_id_1',(to):'book_id_1',(label):'owns'])