图重构-重复关系重构

2022-07-04 14:23:54 浏览数 (1)

今天看到社区有人提问如何进行关系重构,顺手回答了一下。在此记录下关系重构的方法。

- 创建测试数据

代码语言:javascript复制
MERGE (A:Test {name:'A'})
MERGE (B:Test {name:'B'})
CREATE (A)-[:Realation {name:'属性1'}]->(B)
CREATE (A)-[:Realation {name:'属性1'}]->(B)
CREATE (A)-[:Realation {name:'属性2'}]->(B)
CREATE (A)-[:Realation {name:'属性2'}]->(B)
CREATE (A)-[:Realation {name:'属性2'}]->(B)
CREATE (A)-[:Realation {name:'属性3'}]->(B)

- 查询测试数据

代码语言:javascript复制
MATCH p=(A:Test {name:'A'})-->(B:Test {name:'B'}) RETURN p

- 如何重构

代码语言:javascript复制
想请教下大佬,如何删除两个节点间的重复关系,重复的定义指的是,关系的属性不同
比如
(A)-[:Realation{name:‘属性1’]-(B)
(A)-[:Realation{name:‘属性1’]-(B)
(A)-[:Realation{name:‘属性2’]-(B)
(A)-[:Realation{name:‘属性2’]-(B)
(A)-[:Realation{name:‘属性2’]-(B)
(A)-[:Realation{name:‘属性3’]-(B)
想把重复的部分去掉,就是变成
(A)-[:Realation{name:‘属性1’]-(B)
(A)-[:Realation{name:‘属性2’]-(B)
(A)-[:Realation{name:‘属性3’]-(B)

- 重构关系

代码语言:javascript复制
MATCH p=(A:Test {name:'A'})-[r]->(B:Test {name:'B'})
WITH ID(r) AS id,r.name AS name
WITH name,COLLECT(id) AS relIds
WITH name,relIds,SIZE(relIds) AS relIdsSize
WHERE relIdsSize>1
WITH name,apoc.coll.subtract(relIds, [relIds[0]]) AS deleteRelIds
WITH name,deleteRelIds
MATCH ()-[r]-() WHERE ID(r) IN deleteRelIds DELETE r

- 重构结果

- 更多复杂重构可以使用下面的存储过程实现

代码语言:javascript复制
CALL apoc.do.case([relationship=1,'MATCH (from:Label {hcode:$fromHcode}),(to:Label {hcode:$toHcode}) MERGE (from)-[:NEXT]->(to)',relationship=-1,'MATCH (from:Label {hcode:$fromHcode}),(to:Label {hcode:$toHcode}) MERGE (from)<-[:NEXT]-(to)'],'',{fromHcode:fromHcode,toHcode:toHcode}) YIELD value RETURN value

- 社区问答连接

代码语言:javascript复制
http://neo4j.com.cn/topic/5f3b28e4a4477ec754d2b55f

- 推荐一下lyonwj的博客

代码语言:javascript复制
https://www.lyonwj.com/

0 人点赞