1

我有一个用户类定义如下

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

我分别创建了 user_id 1 和 2 user1user2

然后我使用 user1.followings(rel_length: 2). 但结果本身就出来了,user1因为两者user1user2在互相追随。

我已经尝试过order(:breadth_first)和其他方法来排除已经访问过的节点。我可能没有做足够的研究,但有人知道怎么做吗?

4

1 回答 1

1

首先,您可能想使用id_property. 如果您使用propertyforuser_id和 set constraint: :unique,您仍将拥有自动生成的uuid属性。这可能是您想要的,但只是提醒一下。这是文档id_property

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

对于您的问题,您的代码会生成与此类似的 Cypher(我需要更改model_classandrel_class选项):

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

在 Cypher 的单个MATCH子句中,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')
于 2016-04-24T07:49:32.793 回答