0
votes

How to write coalesce gremlin query to create an edge in janusgraph? I create a node1 and then node2 and then create an edge between node1 and node2. I want the edge creation in a way that even when node1/node2 was not created previously, it should be created while creating edge.

2

2 Answers

3
votes

Here is an example of using two coalesce step to create the vertices if they do not exist and then add the edge. Note that I used custom IDs in this example. You may need to use a different scheme with JanusGraph but this is a general pattern you can use. There are other ways you could write this as well but hopefully this gets you started.

g.V('v1').fold().coalesce(unfold(),addV('test').property(id,'v1')).
  V('v2').fold().coalesce(unfold(),addV('test').property(id,'v2')).
  addE('myedge').to(V('v1')) 
3
votes

Let's say there is some property named unique_property which uniquely identifies any node and the label of the node is node. Say we want to add an edge labeled connects between node1 and node2.

g.V().has('node','unique_property','node1').fold()
     .coalesce(unfold(), __.addV('node').property('unique_property','node1'))
     .as('from_node') 
     .coalesce(__.V().has('node','unique_property','node2'), __.addV('node').property('unique_property','node2'))
     .addE('connects')
     .from('from_node')
     .iterate()