2014-02-26 34 views
0

有沒有什麼方法可以根據屬性從Neo4j Dijkstra算法中排除某些特定節點?如何排除一些節點

我知道,我可以在方法中設置允許的relatinoships和方向爲TypeAndDirection,但這並不能幫助我。

假設我有以下代碼:

try (Transaction tx = graphDb.beginTx()) { 

    Node startNode = graphDb.getNodeById(12353); 
    Node endNode = graphDb.getNodeById(12356); 

    CostEvaluator<Double> costEvaluator = new CostEvaluator<Double>() { 
     @Override 
     public Double getCost(Relationship relationship, Direction direction) { 
     Integer cost = Integer.parseInt(relationship.getProperty("cost").toString());    
      return cost.doubleValue(); 
     } 
    };  

    PathFinder<WeightedPath> finder = GraphAlgoFactory.dijkstra(
     PathExpanders.forTypeAndDirection(RelationshipTypes.RELATED, Direction.OUTGOING), costEvaluator); 

     WeightedPath path = finder.findSinglePath(startNode, endNode);   
     System.out.println(path.length()); 
     tx.success(); 
    } 
} 

當Dijkstra算法經過與屬性名稱節點:「倫敦」如何停止執行這條道路,並繼續在其他地方?

回答

1

我最近遇到類似的問題,我需要自定義PathExpander執行一些遍歷。我做這樣的事情(我修改了原代碼有點適合你的情況,但它仍然可能是馬車,所以仔細看):

final private static class FilteringExpander implements PathExpander { 
    private final Direction direction; 

    private FilteringExpander(final Direction direction) { 
     this.direction = direction; 
    } 

    public FilteringExpander() { 
     this.direction = Direction.OUTGOING; 
    } 

    @Override 
    public Iterable<Relationship> expand(Path neoPath, BranchState state) { 
     if (!neoPath.endNode().getProperty("name").equals("London")) { 
      return neoPath.endNode().getRelationships(RelationshipTypes.RELATED, direction); 
     } else { 
      return Collections.emptyList(); 
     } 
    } 

    @Override 
    public PathExpander reverse() { 
     return new FilteringExpander(direction.reverse()); 
    } 
} 

希望這是很清楚。如果您有任何問題,請隨時詢問我。

+0

謝謝,有一個問題。我在第二個覆蓋的變量路徑上出現錯誤,我不確定它是如何工作的。這是我的代碼:http://pastebin.com/wjShzxxA。 – EdWood

+0

@EdWood,這是我的錯,我只是複製粘貼代碼而沒有對流程給予適​​當的關注。現在修復它,再試一次。 – tkroman

+0

@ EdWood,當然沒有任何反應!你還必須使用擴展器,而不是你已經使用的擴展器(作爲'dijkstra'的參數)。你不能指望純粹的類定義的任何東西 - 你也應該實例化它並在某處使用;) – tkroman