cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

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

Hazaaa
Node Link

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 🙂

5 REPLIES 5

ameyasoft
Graph Maven

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;
2X_f_f2cb052cada655088d1b5964d64667e49c8451e1.png

//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;
2X_8_87aa765a00495de0bc87651ca531e0927165469e.png

-Kamal

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

The query is to change the existing relationship type.

: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)

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.