How to create one relationship but delete other one in same query?


(Hazaaa) #1

Hi guys.
I have node user and node post. So user can either like or dislike that post. When he likes post i create LIKED relationship between user and post, but if user then dislike it i will create DISLIKE relationship but LIKED still remains. How can i create one relationship and delete other one?

This is my query:

MATCH (user:User), (post:Post)
WHERE user.username = '...' and post.id = '...'
MEREGE (user)-[liked:LIKED]->(post)
ON CREATE liked
SET liked.time = '...'

Thank you in front guys :)


(Ameyasoft) #2

With apoc.refactor.setType() you can change the relationship type:

// LIKED............................
CREATE (c:User {name:"a"}), (d:Post {id:1})
CREATE (c)-[:LIKED]->(d)
RETURN c, d;
cgrel1

//Change to DISLIKED....................
MATCH (c:User {name:"a"})-[r:LIKED]->(d:Post {id:1})
CALL apoc.refactor.setType(r, 'DISLIKED') YIELD input, output RETURN c, d;
cgrel2

-Kamal


(Hazaaa) #3

But what if liked relationship doesnt exists? Then this second query is useless, am i right?


(Ameyasoft) #4

The query is to change the existing relationship type.


(Chaerry) #5

:param IsLiked: true
MATCH (user:User), (post:Post)
WHERE user.username = '...' and post.id = '...'
//expression when LIKED will create relationship otherwise command will skipped
FOREACH(_ in case when IsLiked then [1] else end | MERGE (user)-[:LIKED]->(post)
//expression when DISLIKED will create relationship otherwise command will skipped
FOREACH(_ in case when not IsLiked then [1] else end | MERGE (user)-[:DISLIKED]->(post)


(Michael Hunger) #6

probably also add an optional match for any relationship
and delete it if it's of the wrong type

in general an unconditional merge and an apoc.setType might be easiest.