Delete all relationships except for those in list

Hi,

I am trying to delete only some of the relationships attached to a node while not deleting those that I have matched by using MATCH then using WHERE NOT EXISTS.
In the example below, I have already created a node (:Person {name:'John'}) and then I MERGE 3 nodes (:Car) with names (test1, test2, test3). However, when I run the query it doesn't delete the intended relationship but instead it deletes all relationships.

UNWIND [{name:'test1'}, {name:'test2'}] AS test
MATCH (p:Person {name:'John'})
OPTIONAL MATCH (p)-[d:DRIVES]->(c:Car)
WHERE NOT EXISTS((p)-[:DRIVES]->(c:Car {name:test.name}))
DELETE d
RETURN p

Thanks in advance :slight_smile:.

Hello @tarendran.vivekanand :slight_smile:

UNWIND [{name:'test1'}, {name:'test2'}] AS test
MATCH (p:Person {name:'John'})-[d:DRIVES]->(c:Car)
WHERE NOT EXISTS((p)-[:DRIVES]->(c:Car {name:test.name}))
DETACH DELETE d

Regards,
Cobra

Hello @cobra :slight_smile:
Unfortunately the query you gave still deletes all relationships :frowning:
Basically im trying to delete all relationships except those that are in the list
Also, I just tested the query works when the list is just 1

UNWIND [{name:'test1'}] AS test

I suggest you to do like this otherwise it will deletes all the elements of the list but keeping the first:

MATCH (p:Person {name:'John'})-[d:DRIVES]->(c:Car)
WHERE NOT c.name IN ['test1', 'test2']
DETACH DELETE d

Regards,
Cobra

1 Like

Thanks @cobra :slight_smile:

However there was a slight error NOT has to come first otherwise will get error.

MATCH (p:Person {name:'John'})-[d:DRIVES]->(c:Car)
WHERE NOT c.name IN ['test1', 'test2']
DETACH DELETE d
1 Like

Oh yeah, Python habits :smile:
I updated my answer, thank you :slight_smile:

1 Like