neo4j - Neo4j-Cypher:从路径中删除一个节点并保持到路径的所有节点的链接
问题描述
我想从路径中删除一个节点,而不危及原始路径节点。
这是我的测试数据库:
我想从路径中删除节点 (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 并取消链接路径
如果没有节点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
解决方案
这是最简单的方法是匹配将被破坏的路径,然后在删除节点的相同密码中创建新链接。
// 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函数创建具有动态类型的关系。
推荐阅读
- swift - SwiftUI 是否向后兼容 iOS 12.x 及更早版本?
- vue.js - 如何等待用户使用 v-model 输入 vue 输入
- asp-classic - 使用经典的 ASP,如何获取或截屏 html 页面的元标记?
- c# - enum.toString() vs Class const string
- selenium - 使用“期望”检查部分文本内容
- r - 如何 gsub 匹配字符串并同时删除不匹配的字符串?
- jmeter - 在 JMeter 属性文件中声明一个全局变量
- r - 我已经在我的 R 中安装了包“xlsx”,但是当尝试打开库“xlsx”时,它警告说包加载失败
- nswag - NSwag 中的自定义模式名称
- amazon-s3 - 拒绝访问 - 使用预签名 URL 的 S3 资源 - Ruby SDK