Neo4j: How to delete all nodes and relationships beyond a node?

可紊 提交于 2019-12-13 05:45:16

问题


Here's a simple graph:

(:a)-[:r]->(:b)

If want to to delete (:b), I can do this with:

MATCH (a)-[r]->(b :b)
DELETE a, r, b

However, (b) can have multiple relationships and nodes coming off of it (and those nodes can recursively have more relationships and nodes too). Something like this:

(:a)-[:r]->(:b)-[:s]->(x)-[:r]->(y)- ... ->(z)

How can I recursively delete every node and relationship beyond (b)?


回答1:


DETACH DELETE is going to be useful here. This first deletes all relationships from a node, then deletes the node itself. That makes your query easier, as all you need is a query for all nodes reachable from your b node.

I'm going to assume for the moment that this b node in your question is a specific node, instead of every single node with the label :b. I do encourage you to reread the developer documentation on variables and labels, as I'm guessing there's a little confusion here.

So, assuming a specific b node, and assuming that it has a name property that differentiates it, you might use this query to delete it and the entire subgraph connected to it and reachable from it.

MATCH (b:b)-[*0..]-(x)
WHERE b.name = 'b'
WITH DISTINCT x
DETACH DELETE x

Note that because we don't care about the relationship type, and because we've specified 0 or more relationships, x will match to b and its entire connected subgraph no matter how many relationships away. Detaching and deleting x will delete all relationships in the subgraph and then all nodes in the subgraph.




回答2:


To delete recursively from a node, you can use path variables: p=(source)-[type*minimumHops..maximumHops]->(target) (by default, minimumHops is 1).

Example dataset:

CREATE
  (a:a)-[:r]->(b:b),
  (b)-[:r]->(c:c),
  (c)-[:r]->(d:d),
  (b)-[:r]->(e:e)

Query:

MATCH (a:a)-[r:r]->(b:b)
OPTIONAL MATCH p=(b)-[:r*]->(c)
DELETE a, r, b, p

An alternative, equivalent query:

MATCH
  (a:a)-[r:r]->(b:b),
  p=(b)-[:r*0..]->(c)
DELETE a, r, p

It's worth noting that both will work in the cornercase where you only have a single (:a)-[:r]->(:b) edge in your graph. The first query does this by specifying the path in an OPTIONAL MATCH, while the second one does it by allowing paths of zero hops.



来源:https://stackoverflow.com/questions/40694257/neo4j-how-to-delete-all-nodes-and-relationships-beyond-a-node

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