Srdjan Marjanovic
Srdjan Marjanovic

Reputation: 372

Delete node and its relationships (if it has any) in Neo4j

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.

Upvotes: 18

Views: 11284

Answers (3)

Sarang
Sarang

Reputation: 2733

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

Upvotes: 1

Lukasz Stelmach
Lukasz Stelmach

Reputation: 5391

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

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

Upvotes: 24

Stefan Armbruster
Stefan Armbruster

Reputation: 39925

There's OPTIONAL MATCH:

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

Upvotes: 19

Related Questions