coderz
coderz

Reputation: 4989

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.

Upvotes: 0

Views: 40

Answers (1)

stephen mallette
stephen mallette

Reputation: 46206

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'])
 

Upvotes: 1

Related Questions