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.

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 .

1 ACCEPTED SOLUTION

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

View solution in original post

5 REPLIES 5

Hello @tarendran.vivekanand

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
Unfortunately the query you gave still deletes all relationships
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

Thanks @Cobra

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

Oh yeah, Python habits
I updated my answer, thank you