Neo4j-Cypher:从路径中删除一个节点,并保持到该路径所有节点的链接

时间:2018-11-12 12:50:18

标签: neo4j path cypher graph-databases

我想从路径中删除一个节点,而又不损害原始路径节点。

这是我的测试数据库:

Test DB

我想从路径中删除节点(2),但是我希望节点1、3、4和5保持链接在路径中。

有没有一种方法可以在一个查询中完成?到目前为止,我有以下内容:

MATCH p = (:Connect)-[:to*]-(:Connect)
WITH nodes(p) AS connectNodes
UNWIND connectNodes AS connectNode
WITH distinct connectNode
WHERE connectNode.connectID = 2
DETACH DELETE (connectNode)

这将删除节点2并取消链接路径

Unlinked graph

如何在没有节点2的情况下保持原始路径的节点之间的链接?

编辑

我通过修改接受的答案来解决

//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 

2 个答案:

答案 0 :(得分:5)

最简单的方法是匹配将要断开的路径,然后在删除节点的相同密码中创建新链接。

// 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

如果要从已删除的关系之一复制类型,可以使用APOC函数来创建具有动态类型的关系。

答案 1 :(得分:1)

另一个机会是删除节点“ 2”并使用APOC过程“重定向关系到”。您可以在procedure documentation中找到详细的说明和图像说明。