Create if not exist Vertex and Edge in 1 Gremlin Query
Asked Answered
L

2

2

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")
)
Landwaiter answered 19/1, 2019 at 10:5 Comment(0)
L
7

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.

Landwaiter answered 21/1, 2019 at 1:47 Comment(0)
C
1

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

Colwin answered 19/10, 2021 at 13:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.