Search code examples
gremlintinkerpoptinkerpop3gremlin-servergremlinjs

Gremlin: What if my query cannot start with V() or E()?


The first query executed on my project runs on a potentially empty database, and creates some vertices if they are not created already, so my query cannot start with V() or E() because the database could be empty, also cannot start with addE() because first I need to check if the edge is not created, I've found the following solution using inject() but it looks like a hack:

g.inject("").union(
    coalesce(V().has("question", "questionId", 0), addV("question").property("questionId", 0)),
    coalesce(V().has("question", "questionId", 1), addV("question").property("questionId", 1)),
    coalesce(V().has("question", "questionId", 2), addV("question").property("questionId", 2))
)

Is there a way to write this in an elegant way without anything that looks hacky?


Solution

  • This scenario can be handled using an upsert pattern via the fold()/unfold() pattern described here. This would look like the code below:

    g.V().
      has("question", "questionId", 0).
      fold().
      coalesce(unfold(), addV("question").property("questionId", 0)).
      V().
      has("question", "questionId", 1).
      fold().
      coalesce(unfold(), addV("question").property("questionId", 1)).
      V().
      has("question", "questionId", 2).
      fold().
      coalesce(unfold(), addV("question").property("questionId", 2))