Create Vertex only if "from" and "to" vertex exists

195 Views Asked by At

I want to create 1000+ Edges in a single query. Currently, I am using the AWS Neptune database and gremlin.net for creating it. The issue I am facing is related to the speed. It took huge time because of HTTP requests. So I am planning to combine all of my queries in a string and executing in a single shot.

_g.AddE("allow").From(_g.V().HasLabel('person').Has('name', 'name1')).To(_g.V().HasLabel('phone').Where(__.Out().Has('sensor', 'nfc'))).Next();

There are chances that the "To" (target) Vertex may not be available in the database. When it is the case this query fails as well. So I had to apply a check if that vertex exists before executing this query using hasNext().

So as of now its working fine, but when I am thinking of combining all 1000+ edge creation at once, is it possible to write a query which doesn't break if "To" (target) Vertex not found?

1

There are 1 best solutions below

3
On

You should look at using the Element Existence pattern for each vertex as shown in the TinkerPop Recipes.

In your example you would replace this section of your query:

_g.V().HasLabel('person').Has('name', 'name1')

with something like this (I don't have a .NET environment to test the syntax):

__.V().Has('person', 'name', 'name1').Fold().
coalesce(__.Unfold(), __.AddV('person').Property('name', 'name1')

This will act as an Upsert and either return the existing vertex or add a new one with the name property. This same pattern can then be used on your To step to ensure that it exists before the edge is created as well.