18

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.

Valentin Grégoire
  • 1,110
  • 2
  • 12
  • 29
Srdjan Marjanovic
  • 375
  • 1
  • 3
  • 11

3 Answers3

24

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

MATCH (movie:Movie {title:"test"})
DETACH DELETE movie
Lukasz Stelmach
  • 5,281
  • 4
  • 25
  • 29
19

There's OPTIONAL MATCH:

MATCH (movie:Movie {title:"test"})
OPTIONAL MATCH (movie)-[r]-() 
DELETE movie, r
Stefan Armbruster
  • 39,465
  • 6
  • 87
  • 97
0

The best option to do this today (Dec 2021) is:

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

See this: https://www.quackit.com/neo4j/tutorial/neo4j_delete_a_relationship_using_cypher.cfm

Sarang
  • 2,143
  • 24
  • 21