2016-04-24 44 views
1

我有定義爲我已經創建user1user2與USER_ID 1和2分別下面搜索第n級的朋友在neo4j.rb在雙向關係圖

class User 
    include Neo4j::ActiveNode 
    include Neo4j::Timestamps 
    property :user_id, type: Integer, constraint: :unique 
    property :max_friends_count, type: Integer, default: 5 
    validates :user_id, :presence => true 
    has_many :out, :followings, model_class: :GraphUser, rel_class: :GraphRel, unique: true 
    has_many :in, :followers, model_class: :GraphUser, rel_class: :GraphRel, unique: true 
end 

用戶類。

然後我使用 user1.followings(rel_length: 2)搜索以下內容。但結果是user1本身,因爲user1user2都是相互關聯的。

我試過order(:breadth_first)和其他方法來排除已經訪問過的節點。我可能沒有做足夠的研究,但有誰知道如何做到這一點?

回答

1

首先,您可能想要使用id_property。如果您使用propertyuser_id並設置爲constraint: :unique,您仍然會自動生成uuid屬性。這可能是你想要的,但只是一個頭。下面是id_property的文檔:

https://github.com/neo4jrb/neo4j/wiki/Neo4j-v3-Unique-IDs

你的問題,你的代碼生成的Cypher與此類似(我需要改變model_classrel_class選項):

MATCH user15573 
WHERE (ID(user15573) = {ID_user15573}) 
MATCH user15573-[rel1:`FOLLOWS`*2]->(result_followings:`User`) 

在單MATCH條款在Cypher中,Neo4j將確保對於單個路徑遍歷,同一關係不會被遍歷多次。但正如你所說,如果他們互相關注,那就意味着它可以按照其他關係返回原始用戶。在可你需要從可能的結果排除原始用戶:

MATCH user15573 
WHERE (ID(user15573) = {ID_user15573}) 
MATCH user15573-[rel1:`FOLLOWS`*2]->(result_followings:`User`) 
WHERE result_followings <> user15573 

在Ruby中,這將是:

user1.as(:source).followings(:target, nil, rel_length: 2).where('source <> target')