Search code examples
rediscyphergraph-theoryredisgraph

redisgraph create edge between nodes if not exist already in high traffic


I have the following cypher query.

MATCH (a:ACTOR {id: 'Charlie'})
MATCH (m:MOVIE {id: 'TwoAndAHalfMen'})
OPTIONAL MATCH (a)-[e:ACTED {prop1: val1}]->(m)
 WITH COUNT(e) AS c, a, m
 WHERE c=0 CREATE (a)-[:ACTED {prop1: val1, prop2: '<cur-time>' }]->(m)

We have an actor node and a movie node. If there is no edge between the actor and the movie nodes, then a new edge ACTED should be created, with some edge properties.

The above query works fine in an idle database with not much traffic, often responding in less than 1 millisecond. However, when there is a lot of traffic, this particular query alone takes a long time, in the order of multiple seconds. While the other queries finish fine.

I suspect that the reason for the slowness is the COUNT function is trying to take all the nodes and somehow gets delayed when there are constant writes. I may be wrong here and just making an assumption.

I do not need to know the total number of edges, and is interested to know only if the edge is there or not. So I tried to do this query in a different way as:

MATCH (a:ACTOR {id: 'Charlie'})
MATCH (m:MOVIE {id: 'TwoAndAHalfMen'})
WHERE NOT EXISTS(
  MATCH (a)-[e:ACTED {prop1: val1}]->(m)
) 
CREATE (a)-[:ACTED {prop1: val1, prop2: '<cur-time>' }]->(m)

But for this I get an error from the redisgraph as:

RedisGraph does not currently support map projection

Is there any other way to optimally create an edge between two nodes if one does not exist already ? I cannot use a MERGE command because the prop2 that I set will be a different value, when I have to create a new edge.

Please note that this should work in redisgraph and not enough if it works on neo4j or some such.


Solution

  • Please see RedisGraph Merge docs more specifically ON MATCH and ON CREATE

    e.g.

    MATCH (a:ACTOR {id: 'Charlie'}), 
          (m:MOVIE {id: 'TwoAndAHalfMen'}) 
    MERGE (a)-[e:ACTED {prop1: val1}]->(m) 
    ON CREATE SET e.prop2 = 'cur-time'