繁体   English   中英

在与neo4j中其他节点具有相同关系的节点之间创建链接列表关系

[英]Create linked list relationship between nodes having same relation to other nodes in neo4j

就像这个图

资料模型

对于数据库中的所有(:A)节点,是否有可能在与同一(:A)节点共享关系[:R]所有(:B)节点之间创建链接列表关系。 如果顺序很重要,则假定所有(:B)节点中都有一个属性order

我假设您在每个:B节点中都有一个order属性。 我正在使用以下示例数据:

CREATE (a1:A)-[:R]->(:B {order : 1}), (a1)-[:R]->(:B {order : 2}), (a1)-[:R]->(:B {order : 3})
CREATE (a2:A)-[:R]->(:B {order : 1}), (a2)-[:R]->(:B {order : 2}), (a2)-[:R]->(:B {order : 3})

然后,您可以使用以下Cypher查询:

// match pairs of :B when b2.order is equal to b1.order plus one
MATCH (a:A)-[:R]->(b1:B), (a)-[:R]->(b2:B)
WHERE b2.order = b1.order + 1
// Create the relation between :B nodes
CREATE (b1)-[:NETX]->(b2)

输出将是:

在此处输入图片说明

另一种选择:使用APOC程序 过程apoc.nodes.link()接收节点的集合,并使用指定的关系类型使它们成为链接列表。 用法示例:

MATCH (A:A)-[:R]->(B:B)
WITH A, B 
ORDER BY B.order ASC
WITH A, collect(B) as bNodes
CALL apoc.nodes.link(bNodes, 'NEXT')
MATCH (A:A)-[:R]->(B:B)
WITH A, 
     B 
ORDER BY B.order ASC // Comment out this line if the order is not important
WITH A, 
     collect(B) as bnodes // List of all nodes of the desired type
UNWIND RANGE(0, size(bnodes)-2) as i // Go through all the nodes except the last one
WITH bnodes[i] as B, 
     bnodes[i+1] as BN
CREATE (B)-[:NEXT]->(BN)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM