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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM