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

3

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.

Auspicious answered 4/4, 2015 at 8:43 Comment(0)
S
19

There's OPTIONAL MATCH:

MATCH (movie:Movie {title:"test"})
OPTIONAL MATCH (movie)-[r]-() 
DELETE movie, r
Stearic answered 4/4, 2015 at 8:51 Comment(2)
How does this work when you have multiple relationships (e.g. when (movie)-[r]-() and ()-[other]-(movie)?Citronellal
You should probably use DETACH DELETE to avoid issues with relationshipsToodleoo
A
24

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

MATCH (movie:Movie {title:"test"})
DETACH DELETE movie
Adeno answered 11/9, 2016 at 13:5 Comment(0)
S
19

There's OPTIONAL MATCH:

MATCH (movie:Movie {title:"test"})
OPTIONAL MATCH (movie)-[r]-() 
DELETE movie, r
Stearic answered 4/4, 2015 at 8:51 Comment(2)
How does this work when you have multiple relationships (e.g. when (movie)-[r]-() and ()-[other]-(movie)?Citronellal
You should probably use DETACH DELETE to avoid issues with relationshipsToodleoo
C
1

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

Circumgyration answered 25/12, 2021 at 6:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.