Create if not exist Vertex and Edge in 1 query gre

2019-06-04 19:22发布

问题:

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.