问题
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