Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update relationship property if previous relationship exists in NEO4J

Tags:

neo4j

cypher

I want to construct a query in cypher that does the following:

  • create a relationship between 2 nodes with a property containing a time duration if no relationship exists already
  • if a relationship is already present, update the time duration property to be the shortest duration of the two relationships

The compare and update part is something that I am not able to achieve in cypher. So any assistence on this part is greatly appreciated.

like image 703
Anton Avatar asked Dec 23 '22 20:12

Anton


1 Answers

You need combine MERGE ON CREATE | ON MATCH and CASE expression. For example:

MATCH (A:City {id: 1})
MATCH (B:City {id: 2})
WITH A, B, toInteger(rand()*100) as newDuration
MERGE (A)-[r:next]->(B)
  ON CREATE SET r.duration = newDuration
  ON MATCH  SET r.duration = CASE 
                                 WHEN r.duration > newDuration 
                                 THEN newDuration 
                                 ELSE r.duration 
                             END
RETURN r.duration
like image 55
stdob-- Avatar answered Feb 08 '23 13:02

stdob--