0

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))
Kelvin Lawrence
  • 14,674
  • 2
  • 16
  • 38
Thirumal
  • 8,280
  • 11
  • 53
  • 103

1 Answers1

1

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.

Kelvin Lawrence
  • 14,674
  • 2
  • 16
  • 38