15
votes

I'm trying to execute following query:

MATCH (movie:Movie {title:"test"})-[r]-() DELETE movie, r

to delete a :Movie node and all its relationships. It's all good, except if the query doesn't have any relationships, it fails to MATCH the movie. I've tried with OPTIONAL MATCH, but no luck.

I'm looking for a way to DELETE a movie node no matter if it has or doesn't have any relationships, but if it has, to DELETE them as well.

2

2 Answers

18
votes

There's OPTIONAL MATCH:

MATCH (movie:Movie {title:"test"})
OPTIONAL MATCH (movie)-[r]-() 
DELETE movie, r
21
votes

In new Neo4j versions (since 2.3 I think) you can use such syntax:

MATCH (movie:Movie {title:"test"})
DETACH DELETE movie