Create if not exist Vertex and Edge in 1 query gremlin

你说的曾经没有我的故事 提交于 2019-12-08 03:10:19

问题


I find the following code to create edge if it has not existed yet.

g.V().hasLabel("V1")
.has("userId", userId).as("a")
.V().hasLabel("V1").has("userId", userId2)
.coalesce(
        bothE("link").where(outV().as("a")),
        addE("link").from("a")
)

It works fine but I want to create both vertices and edge if they are not existed in 1 query.

I try the following code with new graph, it just create new vertices but no relation between them.

g.V().hasLabel("V1")
.has("userId", userId).fold()
.coalesce(
        unfold(),
        addV("V1").property("userId", userId1)
).as("a")
.V().hasLabel("V1").has("userId", userId2).fold()
.coalesce(
        unfold(),
        addV("V1").property("userId", userId2)
)
.coalesce(
        bothE("link").where(outV().as("a")),
        addE("link").from("a")
)

回答1:


Thanks to Daniel Kuppitz in JanusGraph google group. I found out the solution. I re-post it here for anyone who need it.

There are two issues in your query. The first one is the reason why it doesn't work as expected: the fold() step. Using fold() will destroy the path history, but you can easily work around it, by doing that part in a child traversal:

g.V().has("V1","userId", userId1).fold().
  coalesce(unfold(),
           addV("V1").property("userId", userId1)).as("a").
  map(V().has("V1","userId", userId2).fold()).
  coalesce(unfold(),
           addV("V1").property("userId", userId2))
  coalesce(inE("link").where(outV().as("a")),
           addE("link").from("a"))

The second issue is the combination of bothE and outV. You should rather use bothE/otherV, outE/inV or inE/outV.



来源:https://stackoverflow.com/questions/54265985/create-if-not-exist-vertex-and-edge-in-1-query-gremlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!