Thirumal
Thirumal

Reputation: 9536

Get or Create vertex/edge in Apache TinkerPop Gremlin in one query

How to get or create vertex/edge in Apache TinkerPop Gremlin in one query?

Currently I am doing,

id = None
if g.V().has('employee', 'name', 'thirumal').hasNext():
  id = g.V().has('employee', 'name', 'thirumal').values('id')
else:
  id = uuid4()
  g.addV('employee').property(T.id, id).property('name', 'Thirumal').iterate()
logging.debug("Id is {}".format(id))

Upvotes: 0

Views: 424

Answers (1)

Kelvin Lawrence
Kelvin Lawrence

Reputation: 14371

The currently recommended way to do this in Gremlin is to use the fold/coalesce/unfold pattern. In the case of your example it becomes something like:

g.V().has('employee', 'name', 'thirumal').fold().
  coalesce(unfold(),
           addV('employee').property(T.id, id).property('name', 'Thirumal')).
  id().next()

Within the Apache TinkerPop community we are looking at adding additional ways to do this kind of upsert more declaratively, but for now, this is the recommended pattern to use.

This query pattern is discussed more here and here.

Upvotes: 1

Related Questions