【问题标题】:Neo4j- typical query - returning a node with the most appearancesNeo4j - 典型查询 - 返回出现次数最多的节点
【发布时间】:2021-12-06 20:43:59
【问题描述】:

我必须进行查询,返回一个或多个俱乐部,在哪里打球最多的不代表国家的球员,来自哪里。

我的查询工作正常,但我想过滤,所以我的结果是只有尺寸最大的俱乐部。

目前最大的规模是 4 人,我有 4 个俱乐部,应该有 4 名球员。

我想到过滤掉它的唯一方法是最后使用LIMIT 1,但随后,我剪掉了三个梅花,它们也填充了谓词。

MATCH (c: Club)<-[r: PLAYS_FOR]-(p: Player)-[r2: REPRESENTS]->(n: NationalTeam)
WHERE c.country<>n.country
WITH c,collect(p.name) as list_players,n.country as country,size(collect(p.name)) as size
RETURN c,list_players,country,size ORDER BY size DESC LIMIT 1

编辑:

我设法做了这样的事情,不知道它是否是最佳的,但它正在工作:

MATCH (c: Club)<-[r: PLAYS_FOR]-(p: Player)-[r2: REPRESENTS]->(n: NationalTeam)
WHERE c.country<>n.country
WITH c,collect(p.name) as list_players,n.country as country,size(collect(p.name)) as size
WITH c,list_players,country,size ORDER BY size DESC LIMIT 1
WITH size
MATCH (c: Club)<-[r: PLAYS_FOR]-(p: Player)-[r2: REPRESENTS]->(n: NationalTeam)
WHERE c.country<>n.country
WITH size,c,collect(p.name) as list_players,n.country as country,size(collect(p.name)) as size2 WHERE size(collect(p.name)) = size
RETURN c,list_players,country,size

【问题讨论】:

    标签: neo4j


    【解决方案1】:

    如果您安装 APOC 程序,则可以使用聚合函数来获取与最大值相关联的项目,即使多个项目与该值相关联时也可以使用:apoc.agg.maxItems()

    现在的问题是所有特定于俱乐部的数据都需要封装到项目本身中,因此您需要将它们添加到地图并将地图用作项目,并将人员集合的大小作为价值。

    您的聚合也不完全正确。您正在收集玩家姓名,但您将玩家所在的国家/地区作为分组键的一部分(当您聚合时,所有非聚合术语形成分组键),这可能不是您想要的。也许您想要的是俱乐部所在的国家/地区?

    尝试从这里开始工作:

    MATCH (c: Club)<-[r: PLAYS_FOR]-(p: Player)-[r2: REPRESENTS]->(n: NationalTeam)
    WHERE c.country<>n.country
    WITH c,collect(p) as list_players
    WITH apoc.agg.maxItems({club:c, players:list_players}, size(list_players)) as maxResults
    UNWIND maxResults.items as result
    WITH result.club as c, [player IN result.players | player.name] as list_players, maxResults.value as size
    RETURN c,list_players,size 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多