How to check if an edge exists

Hi,

I want to run a query that adds edges between nodes on some conditions.
The thing is that I only want to make the edge if it’s not existed yet.

for example:
CREATE QUERY create_infected_edge(/* Parameters here /) FOR GRAPH movies SYNTAX V2{
/
Write query logic here */
Result = SELECT a1 from ACTOR:a1-(ANY)-MOVIE:m-(ANY)-ACTOR:a2
WHERE a1 != a2
ACCUM
INSERT INTO infected VALUES (a1, a2, to_datetime(to_string(m.year)+"-01-01"));

PRINT “create_infected_edge works!”;
}

how can I make sure that there is no edge between a1 and a2 and only then add the edge?

Thanks

You have two options. One is to add the edge anyway (you can only have one edge so this should be okay).

The other is to extend your WHERE clause e.g.:
getvid(a1)<getvid(a2) AND a1.outdegree(“infected”) == 0 ;

This won’t guarantee the edge will only be inserted once, but it will skip existing edges. I haven’t tested this, so it is possible there may be other issues with my code, but hopefully you get the idea.

The getvid() thing is so a pair is only counted once, and will also avoid self edges.

1 Like

I’ll check it out. thanks!!

1 Like