简体   繁体   中英

How to delete a node and its connected nodes with Neo4j cypher query?

For example, I want to delete Actor node with id = "005A" and its connected Movie nodes. The relationship between Actor and Movie node is ACTED_IN .

I have tried this cypher query:

MATCH (a:Actor {id: "005A"})
OPTIONAL MATCH (a)-[r:ACTED_IN]->(m)
DELETE a, r, m;

but it didn't work, I got TransactionFailureException: Unable to commit transaction error.

Anyone can give a solution?

UPDATE:

I found out that there is relationship from other node ( Agency ) to Actor node which labeled as OWNED . So the diagram is like this:

(aa:Agency)-[o:OWNED]->(a:Actor)

[EDITED]

You cannot delete a node unless all of its relationships have also been deleted. In your case, it is possible that the a and/or m nodes have relationships other than r .

To get the set of relationship types associated with a and m , you can use the following (I've limited the result to 10 rows, in case a and/or m have a lot of relationships`):

MATCH (a:Actor {id: "005A"})
OPTIONAL MATCH ()-[rx]-(a)
OPTIONAL MATCH (a)-[r:ACTED_IN]->(m)
OPTIONAL MATCH (m)-[ry]-()
RETURN a, r, m, COLLECT(DISTINCT TYPE(rx)), COLLECT(DISTINCT TYPE(ry))
LIMIT 10;

I suspect that your results will show types other than ACTED_IN .

The following query should delete the actor and all movies s/he acted in:

MATCH (a:Actor {id: "005A"})
OPTIONAL MATCH ()-[rx]-(a)
OPTIONAL MATCH (a)-[r:ACTED_IN]->(m)
OPTIONAL MATCH (m)-[ry]-()
DELETE rx, ry, r, a, m;

Are you sure the id is encoded as a string property ? I guess the id of the movie database is an integer and thus the id should not be encapsulated in quotes :

MATCH (a:Actor {id: 5})
OPTIONAL MATCH (a)-[r:ACTED_IN]->(m)
DELETE a, r, m;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM