Neo4j how to delete nodes recursively from some start node

亡梦爱人 提交于 2019-12-02 02:19:35

I'd split that up into two queries. The first one recursively collects the the product hierarchy downwards and the second one deletes one product node and its direct environment.

Getting the product hierarchy is simple:

MATCH (p:Product)-[:CONTAINS*]->(childProduct)
WHERE id(p) = {productId}
RETURN id(childProduct) as id

To delete one product we need to delete all relationships of that product node. Additionally all related nodes need to be deleted as well if they are neither user (you want to keep them) or products (think of parent products - they should be kept as well). Also we need to be sure the target nodes are not connected, thats's why the 2nd optional match:

MATCH (p:Product) 
OPTIONAL MATCH (p)-[r]-(t)
WHERE id(p) = {productId}
DELETE r,p
WITH t
OPTIONAL MATCH (t)-[r2:VOTE_ON|:CREATED_BY]->()
WHERE none(x in labels(t) WHERE x in ["User", "Product"])
DELETE t,r2

I did not test this query myself since you didn't provide a test graph. So take this as an idea and modify it until it works.

update

In a chat we found that this cypher statement solves the problem, note that Product has been replaced by Decision label in the model:

MATCH (p:Decision) 
WHERE p.name = "NoSQL" 
WITH p 
OPTIONAL MATCH (p)-[r]-(t) 
DELETE p,r 
WITH t,r 
OPTIONAL MATCH (t)-[r2:VOTED_ON|:CREATED_BY|:VOTED_FOR]-() 
WITH t, r2,r 
WHERE none(x in labels(t) WHERE x in ["User", "Decision"]) 
DELETE t,r2
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!