You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Neo4j查询需求:在用户帖子反应统计中新增总反应数列

解决方案

可以通过窗口函数实现需求,既保留原有统计字段,又新增每个帖子发布者的总反应数。以下是两种可行的修改方案:

方案一:分步聚合(逻辑更清晰)

MATCH (z:User)-[re:REACTED]->(p:Post)<-[:POSTED]-(x:User) 
WHERE exists(re.type) 
WITH x.name as postOwner, re.type as rectionType, count(re) as noOfReactions, collect(re.type) as reactionList
WITH postOwner, rectionType, noOfReactions, reactionList, sum(noOfReactions) OVER (PARTITION BY postOwner) as totalReactions
RETURN postOwner, rectionType, noOfReactions, reactionList, totalReactions

方案二:直接在返回语句中使用窗口函数(写法更简洁)

MATCH (z:User)-[re:REACTED]->(p:Post)<-[:POSTED]-(x:User) 
WHERE exists(re.type) 
RETURN x.name as postOwner, 
       re.type as rectionType, 
       count(re) as noOfReactions, 
       collect(re.type) as reactionList,
       count(re) OVER (PARTITION BY x.name) as totalReactions

核心说明

  • 窗口函数OVER (PARTITION BY x.name)会忽略当前按postOwner和rectionType的分组,单独统计每个用户名下所有反应的总数,完美匹配需求。
  • 给collect(re.type)命名为reactionList是为了字段名更规范,你也可以保留原写法不命名。

内容的提问来源于stack exchange,提问作者Surya Teja Patkari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 21:20:51