简体   繁体   English

限制关系中公共节点的数量-Neo4j

[英]Limiting amount of common nodes in a relationship - Neo4j

Say I have a nodes person and movie with a relation of [likes]. 假设我有一个节点人和一部电影,具有[喜欢]的关系。 I am trying to be able to limit the amount of persons that like the same movie without limiting my results to only include 1 movie. 我试图限制喜欢同一部电影的人数,而不将我的搜索结果限制为仅包含一部电影。

For example: 例如:

    MATCH (p:Person)-[LIKES]->(m:Movie)
    WHERE
    p.age < 30
    p.gender = "Male"
    RETURN p,m

So in the query above I would like to get all the results but filter them so that only 2 Persons will like the same movie. 因此,在上面的查询中,我希望获得所有结果,但要对其进行过滤,以便只有2个人会喜欢同一部电影。

Is this possible? 这可能吗?

This knowledge base article goes over different ways to limit match results per row . 这篇知识库文章介绍了各种方法来限制每行的匹配结果

For a non-APOC approach you can get the slice of the collection of people who liked the movie: 对于非APOC方法,您可以从喜欢这部电影的人中收集一部分:

MATCH (p:Person)-[:LIKES]->(m:Movie)
WHERE
p.age < 30
p.gender = "Male"
RETURN m, collect(p)[..2] as peopleWhoLiked

If you want a separate row per person, then UNWIND the peopleWhoLiked list before the return. 如果要每人单独一行,请在返回之前取消peopleWhoLiked列表。

For the second approach, you'll need APOC Procedures. 对于第二种方法,您将需要APOC程序。

In order to use LIMIT, you'll need to first match on all movies, then perform the limited match to :Person nodes using apoc.cypher.run() . 为了使用LIMIT,您需要首先在所有电影上进行匹配,然后使用apoc.cypher.run()对:Person节点执行受限匹配。

To get all movies that have exactly two (under-30 male) likers: 要获得具有两个(不超过30个男性)喜欢者的所有电影,请执行以下操作:

MATCH (p:Person)-[:LIKES]->(m:Movie)
WHERE
  p.age < 30 AND
  p.gender = "Male"
WITH m, COLLECT(p) AS likers
WHERE SIZE(likers) = 2
RETURN m, likers;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM