[转载]Neo4j查询节点间最短路径
2022-01-28 本文已影响0人
thirsd
1.指定某一结点
无向边:
MATCH (p1:Person {name:"aaaaaaa"}),(p2:Person{name:"bbbbbb"}),
p=shortestpath((p1)-[*..10]-(p2))
RETURN p
有向边:
MATCH (p1:Person {name:"aaaaaaa"}),(p2:Person{name:"bbbbbb"}),
p=shortestpath((p1)-[*..10]->(p2))
RETURN p
注:[*…10]表示查询路径长度10以内的关系
同时返回最短路径长度:
MATCH (p1:Person {name:"aaaaaaa"}),(p2:Person{name:"bbbbbb"}),
p=shortestpath((p1)-[*..10]->(p2))
RETURN p,length(p)
添加限制条件
1)只经过标签为“rrrr”的边:
MATCH (p1:Person {name:"aaaaaaa"}),(p2:Person{name:"bbbbbb"}),
p=shortestpath((p1)-[r:rrrr*..10]->(p2))
RETURN p
2)不经过属性值idp为"xxxx"的结点:
MATCH (p1:Person {name:"aaaaaaa"}),(p2:Person{name:"bbbbbb"}),
p=shortestpath((p1)-[*..10]->(p2))
where all(x in nodes(p) where x.idp<>"xxxx")
RETURN p
2)不经过属性值idr为"yyyy"的边:
MATCH (p1:Person {name:"aaaaaaa"}),(p2:Person{name:"bbbbbb"}),
p=shortestpath((p1)-[r*..10]->(p2))
where all(x in r where x.idr<>"yyyy")
RETURN p
2.指定某一类结点
(边的有向无向、限制条件同上,此处不再分别叙述)
match (p:Person) with collect(p) as nodes
unwind nodes as source
unwind nodes as target
with source,target where id(source)<>id(target)
match paths = shortestPath((source)-[*..10]->(target))
with paths limit 25
return path
返回所有最短路径
match (p:Person) with collect(p) as nodes
unwind nodes as source
unwind nodes as target
with source,target where id(source)<>id(target)
match paths = allShortestPaths((source)-[*..10]->(target))
with paths limit 25
return path
with source,target where id(source)<>id(target)
此处是为了保证起始和最终结点不相同。
————————————————
版权声明:本文为CSDN博主「少羽baby」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_34233510/article/details/83110854