简体   繁体   中英

Create if not exist Vertex and Edge in 1 Gremlin Query

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

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 .

I used the approach suggested by @thangdc94 (thanks!) and found that the "map" step takes a long time, this query worked much faster (X20) for me:

g.V().has("V1","userId", userId1).fold().
  coalesce(unfold(),
           addV("V1").property("userId", userId1)).as("a").iterate();
  g.V().has("V1","userId", userId2).fold().
  coalesce(unfold(),
           addV("V1").property("userId", userId2)).as("b").
  V().has("V1","userId", userId1).
  coalesce(outE("link").where(inV().as("b")),
           addE("link").to("b"))

comment: I used Neptune DB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM