简体   繁体   中英

Gremlin query to update the vertex property if exists or create new vertex with property

i am trying to upsert vertex if exists, if does not exists create new vertex and add property. as ID is immutable, cannot update id? how to drop and add it with same query. what is wrong with the below code?

g.V().hasId(sampleVertex.getId()).fold()
    .coalesce(
      _.unfold()
        .property("name",sampleVertex.getName())
        .property("age",sampleVertex.getAge())
        .property("networth",sampleVertex.getNetworth())
        .property("picURL",sampleVertex.getPicURL())
        .property("description",sampleVertex.getDescription()),
      _.addV(sampleVertex.getLabel())
            .property(T.id,sampleVertex.getId())
            .property("name",sampleVertex.getName())
            .property("age", sampleVertex.getAge())
            .property("networth", sampleVertex.getNetworth())
            .property("picURL", sampleVertex.getPicURL())
            .property("description",sampleVertex.getDescription())
).next();
}

I think you have some extra . in the query. You don't need them in front of the first steps for each of the arguments inside of coalesce() . You could also simplify this query by placing the common property() steps after the coalesce() as the output of that step would be the existing or newly created vertex.

g.V().
  hasId(sampleVertex.getId()).
  fold().
  coalesce(
    unfold(),
    addV(sampleVertex.getLabel()).
        property(T.id, sampleVertex.getId())
    ).
    property("name", sampleVertex.getName()).
    property("age", sampleVertex.getAge()).
    property("networth", sampleVertex.getNetworth()).
    property("picURL", sampleVertex.getPicURL()).
    property("description", sampleVertex.getDescription().
    next()

If you wanted to drop the vertex in order to change the ID, then you would need to do something like:

g.V().
  hasId(sampleVertex.getId()).
  fold().
  coalesce(
    unfold().sideEffect(drop()).
    addV(sampleVertex.getLabel()).
        property(T.id, sampleVertex.getId()),
    addV(sampleVertex.getLabel()).
        property(T.id, sampleVertex.getId())
    ).
    property("name", sampleVertex.getName()).
    property("age", sampleVertex.getAge()).
    property("networth", sampleVertex.getNetworth()).
    property("picURL", sampleVertex.getPicURL()).
    property("description", sampleVertex.getDescription().
    next()

Just realize that dropping a vertex also drops all related edges to that vertex at the same time. If you want to maintain any existing edges, you'll likely want to fetch those in a separate query before this and then recreate them afterwards.

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