Neo4j 查找返回同一节点的所有路径

Neo4j Find all paths back to the same node

我有实体(例如 A、B、C)可以发送一种或多种协议(TCP、UDP 和 FTP)并且可以接收一种或多种协议,如下图所示。

我想创建一个密码查询,它将找到从给定实体返回到同一实体的所有可能路径,根据跃点数从最短路径到最长路径排序。

可以在 neo4j Console 在线测试,使用以下创建脚本:

create (a:Entity {name:'A'}), 
(b:Entity {name: 'B'}), 
(c:Entity {name: 'C'}), 
(d:Entity {name: 'D'}),  
(tcp:Protocol {name: 'TCP'}),  
(ftp:Protocol {name: 'FTP'}),  
(udp:Protocol {name: 'UDP'}),  
(a)-[:SEND]->(tcp), (tcp)-[:SEND]->(b), (tcp)-[:SEND]->(d), (b)-[:SEND]->(ftp), (ftp)-[:SEND]->(c), (ftp)-[:SEND]->(d), 
(d)-[:SEND]->(udp), (c)-[:SEND]->(udp), (udp)-[:SEND]->(a)

确保先点击顶部栏的清除数据库

MATCH path=(source { name:'A' })-[r*4..10]-> source
RETURN path, length(path)/2-1 AS hops
ORDER BY hops

解释:

{ name:'A' } - 用于标识源节点

[4..10] - 用于指定最小和最大跳数(包括)。在这种情况下,低于 4 跳是不可能的,因为最小跳数是 4:

实体 -> 协议 -> 实体 -> 协议 -> 实体

length(path)/2-1 AS hops - 计算路径中存在多少实体跃点。请注意,length(path) 包含实体和协议。