簡體   English   中英

Neo4J-Cypher:多個節點之間的最短路徑

[英]Neo4J - Cypher: shortest path between multiple nodes

假設我們有4個節點:

{id:1, name:"one"} {id:2, name:"two"} {id:3, name:"three"} {id:4, name:"four"}

假設節點1鏈接到節點2,節點2到3,3到4,則結果將類似於:

(1)-->(2)-->(3)-->(4)

如何以給定順序獲得多個給定節點之間的最短路徑? 一些例子:

findShortestPath(2,4,3)應導致: (2)-->(3)-->(4)

findShortestPath(3,1)應導致: (1)-->(2)-->(3)

findShortestPath(4,1)應導致: (1)-->(2)-->(3)-->(4)

findShortestPath(3,2)應導致: (2)-->(3)

我已經嘗試過類似的方法,但是我覺得我走錯了路,這不是最有效的解決方案。 請注意,我的查詢以編程方式構造,因為它可以包含任意數量和種類的節點。

如果輸入為:(2),(3),(1)

這將導致double for循環構造如下內容:

match p=allShortestPaths((p2)-[*]-(p3)),allShortestPaths((p2)-[*]-(p1)),allShortestPaths((p3)-[*]-(p1)) where p1.name="Keanu Reeves" and p2.name="Gene Hackman" and p3.name="Clint Eastwood" return p;

我的問題是我無法為allShortestPaths()函數提供多個節點。 只允許2個具有1個關系的節點。

您可以遍歷所有節點對,並檢查其他節點是否在這些對之間的可能路徑中:

WITH ["Keanu Reeves", "Gene Hackman", "Clint Eastwood"] AS names
UNWIND names AS nn
  MATCH (n {name: nn})
  WITH collect(n) AS nds

UNWIND nds AS n1
  UNWIND nds AS n2
  WITH nds, n1, n2 WHERE id(n1) > id(n2)
    MATCH path = allShortestPaths((n1)-[*]-(n2))
    WITH nds, path WHERE ALL(n IN nds WHERE n IN nodes(path))
RETURN path ORDER BY length(path) ASC

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM