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

我是研究僧i 提交于 2019-12-13 03:36:12

问题


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)

回答1:


[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;



回答2:


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;


来源:https://stackoverflow.com/questions/27929383/how-to-delete-a-node-and-its-connected-nodes-with-neo4j-cypher-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!