简体   繁体   中英

Cypher: Node not found in same query

I have this test database:

在此处输入图片说明

I want to remove that path with two +B nodes to the right. This case generally can be described as a path, that contains PS nodes ( +B nodes are also PS nodes, that do not have an incoming :SOURCE edge. The sub path I want to delete is the one between (writer) (excluding) and and that node that has no incoming :SOURCE edge (including).

For that I have this query:

MATCH p1=(writer:A {type:'writer'})-[*]->(Q:PS)-[:TARGET*]->(T)
WITH (Q), (writer)
MATCH (Q)
WHERE NOT ()-[:SOURCE]->(Q)
WITH (Q), (writer)

MATCH p2=(writer)-[*]->(Q)
WHERE ANY (x IN NODES(p2)[1..] WHERE x:PS AND NOT ()-[:SOURCE]->(x))

WITH REDUCE(s = [], y IN NODES(p2)[1..] | CASE
  WHEN y:PS THEN s + y
  ELSE s END) AS todo
FOREACH (z IN todo | DETACH DELETE z);

It first identifies the said node(s) and then passes them on to make a new path selection, that ends in that node. This all works correctly. What does not work is the very last part beginning with WITH REDUCE . It says it does not find Q , but Q does not even occur in that part.

The error is Node <some ID> not found . Why is that? Why does it not find the node again and why does it even try to in the last part? Cutting the last part off and the query works as intended up to that point.

[UPDATED]

That error typically means that you are trying to delete a node that has already been deleted, or to delete a relationship that has an endpoint node that has already been deleted.

Try replacing your FOREACH clause with the following snippet, which eliminates duplicate nodes before attempting to delete them, and also deletes the relationships before the nodes:

UNWIND todo AS node
WITH DISTINCT node
MATCH (node)-[r]-()
WITH COLLECT(DISTINCT node) AS nodes, COLLECT(DISTINCT r) AS rels
FOREACH(r IN rels | DELETE r)
FOREACH(n IN nodes | DELETE n);

Also, your query seems to very inefficient. Here is a simpler version, which includes the above fix:

MATCH p=(:A {type:'writer'})-[*]->(:PS)-[:TARGET]->()
WHERE ANY (x IN NODES(p)[1..-1] WHERE x:PS AND NOT ()-[:SOURCE]->(x))
WITH REDUCE(s = [], y IN NODES(p)[1..] | CASE
  WHEN y:PS THEN s + y
  ELSE s END) AS todo
UNWIND todo AS node
WITH DISTINCT node
MATCH (node)-[r]-()
WITH COLLECT(DISTINCT node) AS nodes, COLLECT(DISTINCT r) AS rels
FOREACH(r IN rels | DELETE r)
FOREACH(n IN nodes | DELETE n);

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