Reputation: 168
I want to remove one node from a path, without jeopardizing the original path nodes.
This is my test db:
I want to remove node (2) from the path, but I want nodes 1, 3, 4, and 5 to stay linked in the path.
Is there a way to do it in one query? So far I have the following:
MATCH p = (:Connect)-[:to*]-(:Connect)
WITH nodes(p) AS connectNodes
UNWIND connectNodes AS connectNode
WITH distinct connectNode
WHERE connectNode.connectID = 2
DETACH DELETE (connectNode)
This will remove node 2 and unlinkes the path
How can maintain the link between the nodes of the original path without node 2?
EDIT:
I solved it by modifying the accepted answer's response
//Make sure node (n) belongs to the path
MATCH (n:Connect {cID:2})-[:to*]-(:Connect {cID:5})
//get attached nodes, if any, ignoring directions
OPTIONAL MATCH (oa:connect)-[:to]-(n)-[:to]-(ob:connect)
//make sure nothing is duplicated
WHERE oa.cID <> ob.cID
//Use FOREACH to mimic if/else. Only merge oa to ob if they exist. Query fails without it
FOREACH (_ IN case when oa IS NOT NULL then [true] else [] end |
MERGE (oa)-[:to {created: 1542103211}]-(ob)
)
//Get n, and get all connected nodes to it, and delete the relationship(s)
WITH n
OPTIONAL MATCH (n)-[r:to]-(:Connect) DELETE r
Upvotes: 1
Views: 952
Reputation: 1284
An additional opportunity would be the removal of node "2" and the usage of the APOC procedure "Redirect relationship to". You can find a detailed description and illustrating images in the procedure documentation.
Upvotes: 1
Reputation: 8833
This is the simplest way to do it would be to match the paths that would be broken, and then create the new links in the same cypher that deletes the node.
// Match the target node for deletion
MATCH (n{id:2})
// Match broken paths, if any
OPTIONAL MATCH (a)-[ra]->(n)-[rb]->(b)
// Create new link to replace destroyed ones
CREATE (a)-[r:to]->(b)
// Copy properties over, if any
SET r+=ra, r+=rb
// Remove target node
DETACH DELETE n
// If you want to keep the node and just disconnect it, replace last line with
// OPTIONAL MATCH (n)-[r:to]-() DELETE r
There are APOC functions you can use to create a relation with a dynamic type if you want to copy the type from one of the removed relationships.
Upvotes: 5