Gremlin:如果我的查询不能以 V() 或 E() 开头怎么办?

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

在我的项目上执行的第一个查询在一个可能为空的数据库上运行,并创建一些尚未创建的顶点,因此我的查询不能以 V()E() 开头,因为数据库可能是空的,也不能以 addE() 开头,因为首先我需要检查是否没有创建边缘,我使用 inject() 找到了以下解决方案,但它看起来像 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))
)

有没有办法以一种优雅的方式来写这个而没有任何看起来很 hacky 的东西?

这种情况可以通过 here 描述的 fold()/unfold() 模式使用更新插入模式来处理。这看起来像下面的代码:

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