Tarendran Vivekananda
Tarendran Vivekananda

Reputation: 15

Neo4j:Delete all relationships except for those in list

I am trying to delete all relationships to a node except those that are in a list. I have already create a node (:Person {name: 'John'}) and 4 other nodes (:Car). Then I MERGE all the car nodes to the person node. I then want to delete all the relationships for the person node except for those in a list (shown below)

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 

However the query above deletes all relationships but when I reduce the list to include only 1 car node, the above query works (i.e. the query only works when the list contains only 1 node and doesn't work when the list is larger). I am not sure why this is the case.

I am using neo4j 4.1. Thanks in advance.

Upvotes: 0

Views: 363

Answers (1)

cybersam
cybersam

Reputation: 66947

This should work:

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

and also this:

WITH ['test1', 'test2'] AS tests
MATCH (p:Person {name: 'John'})
FOREACH(x IN [(p)-[d:DRIVES]->(c:Car) WHERE NOT c.name IN tests | d] | DELETE x)
RETURN p

Upvotes: 1

Related Questions