Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

neo4j

cypher

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.

like image 410
Srdjan Marjanovic Avatar asked Apr 04 '15 08:04

Srdjan Marjanovic


People also ask

How do I delete all nodes and relationships in Neo4j?

Deleting Nodes and Relationships Deleting all nodes and relationships in a Neo4j database is very simple. Here is an example that does just that: MATCH (n) DETACH DELETE n; The DETACH keyword specifies to remove or “detach” all relationships from a particular node before deletion.

How do I delete a particular relationship in Neo4j?

Deleting relationship is as simple as deleting nodes. Use the MATCH statement to match the relationships you want to delete. You can delete one or many relationships or all relationships by using one statement.

How do I remove a property from Neo4j?

The REMOVE clause is used to remove properties and labels from graph elements (Nodes or Relationships). DELETE operation is used to delete nodes and associated relationships. REMOVE operation is used to remove labels and properties.


2 Answers

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

MATCH (movie:Movie {title:"test"})
DETACH DELETE movie
like image 148
Lukasz Stelmach Avatar answered Oct 22 '22 07:10

Lukasz Stelmach


There's OPTIONAL MATCH:

MATCH (movie:Movie {title:"test"})
OPTIONAL MATCH (movie)-[r]-() 
DELETE movie, r
like image 25
Stefan Armbruster Avatar answered Oct 22 '22 05:10

Stefan Armbruster