2013-10-20 26 views

回答

12

給定兩個節點 「nodeA上」 和 「節點B」,

  1. 獲取連接到 「nodeA上」 所有的關係,

    rels = nodeA.getRelationships(); 
    
  2. 迭代通過關係 「RELS」 的集合,每個關係「rel」,測試另一個節點是否爲節點B

    rel.getOtherNode(nodeA).equals(nodeB) 
    
  3. 如果上述表達式適用於其中一個關係,則nodeA和nodeB已連接。

這裏是一個 「節點」 和 「Relationshiip」 了Java API,

http://api.neo4j.org/current/

+2

我只是想我要補充,您應該在執行此搜索之前考慮'nodeA'和'nodeB'的邊數,因爲您可以從任一節點開始執行。 –

+2

如果您可能擁有數千個關係,則這不起作用。 – davedonohue

0
private boolean sharedRelationshipExists(Node nodeA, long nodeBId) 
{ 
    Iterator<Relationship> iterator = nodeA.getRelationships().iterator(); 
    while (iterator.hasNext()) 
    { 
     if (iterator.next().getOtherNode(nodeA).getId() == nodeBId) return true; 
    } 
    return false; 
} 

// in another part 
boolean sharedRelationshipBetweenAB; 
if (nodeA.getDegree() < nodeB.getDegree()) 
{ 
    sharedRelationshipBetweenAB = sharedRelationshipExists(nodeA, nodeB.getId()); 
} 
else 
{ 
    sharedRelationshipBetweenAB = sharedRelationshipExists(nodeB, nodeA.getId()); 
} 

布爾sharedRelationshipBetweenAB將持有你的答案

相關問題