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

如何编写Elasticsearch聚合查询实现按用户分组统计关系值总和

正确查询语句

你之前的方案问题在于仅做了单层聚合,未嵌套统计对端用户的分值总和,也没有覆盖用户在userA、userB两个位置的双向场景。以下是可直接使用的查询,一次返回所有需要的统计数据:

GET myindex*/_search
{
  "size": 0,
  "query": {
    "bool": {
      "filter": [
        {
          "terms": {
            "userA": ["<输入的用户ID列表>"]
          }
        },
        {
          "terms": {
            "userB": ["<输入的用户ID列表>"]
          }
        }
      ]
    }
  },
  "aggs": {
    "user_as_a": {
      "terms": {
        "field": "userA",
        "size": 1000
      },
      "aggs": {
        "peer_user": {
          "terms": {
            "field": "userB",
            "size": 1000
          },
          "aggs": {
            "relation_sum": {
              "sum": {
                "field": "relation"
              }
            }
          }
        }
      }
    },
    "user_as_b": {
      "terms": {
        "field": "userB",
        "size": 1000
      },
      "aggs": {
        "peer_user": {
          "terms": {
            "field": "userA",
            "size": 1000
          },
          "aggs": {
            "relation_sum": {
              "sum": {
                "field": "relation"
              }
            }
          }
        }
      }
    }
  }
}

结果处理规则

查询返回后按以下规则合并数据即可得到你需要的输出格式:

  1. 遍历user_as_a聚合下的所有桶:桶key为当前用户,内层peer_user的桶key为对端用户,桶内relation_sum的值为对应关系分值
  2. 遍历user_as_b聚合下的所有桶:桶key为当前用户,内层peer_user的桶key为对端用户,桶内relation_sum的值为对应关系分值
  3. 相同当前用户、相同对端用户的分值直接相加,最终输出结构和你要求的完全一致。

如果你的业务中relation是userA到userB的单向值,不需要双向统计,去掉user_as_b的聚合部分即可。size参数可根据你的用户列表实际长度调整,避免数据被截断。

内容的提问来源于stack exchange,提问作者ym_wp

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 19:36:04