Neo4j查询节点间最短路径
Neo4j最短路径问题
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)
此处是为了保证起始和最终结点不相同。
注:两个unwind把结点集合打散,并以笛卡尔积的形式组成结点对。
参考:https://blog.csdn.net/wry2008wry/article/details/80762811
原文地址:https://blog.csdn.net/qq_34233510/article/details/83110854 </div>