Raja
Raja

Reputation: 442

Neo4J Query Create new or Replace existing Relationship

I have a scenario in which I will have to create nodes for a new relationship or if nodes exist and a relationship exists, I have to replace the existing relationship with new one. Only one relationship will exist between 2 nodes.

Below commands doesn't seem to be working when I call from Python client using GDB.query:

match (a:user)-[r]->(b:user)
where a.id='3' and b.id='5' 
merge (a)-[r2:test]->(b)
SET r2 = r SET r2.percentage = 80
WITH r
DELETE r
return r

MATCH (a:user),(b:user)
WHERE a.id='3' AND b.id='5'
MERGE (a)-[r:test]->(b) 
RETURN r

Upvotes: 2

Views: 614

Answers (2)

Raja
Raja

Reputation: 442

Finally, got the right query. First we execute the match and if it doesn't work, we execute the second query which does a create, if it already exists, it doesn't do anything.

match (a:user)-[r]->(b:user) 
where a.id=3 and b.id=5 
merge (a)-[r2:test4]->(b) 
set r2.percentage = 50 
delete r 
return a,b, r2

MERGE (a:user {id:3})-[r:test]->(b:user {id:5}) 
ON CREATE 
SET r.percentage = 55
ON MATCH
SET r.percentage = 55

Upvotes: 0

Luanne
Luanne

Reputation: 19373

If you want to replace an existing relationship of a particular type with a new one:

match (a:user {id:'3'})
match (b:user {id:'5'})
merge (a)-[newRel:NEW_TYPE]->(b) //create the new rel if missing 
set newRel.percentage = 80
match (a)-[oldRel:OLD_TYPE]->(b) //match the old rel
delete oldRel //and delete it

But if you just want to set a property on an existing relationship and create it if missing:

match (a:user {id:'3'})
match (b:user {id:'5'})
merge (a)-[rel:REL_TYPE]->(b) //creates a new rel if it doesn't exist
set rel.percentage = 80

Upvotes: 4

Related Questions