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

如何编写Elasticsearch查询统计user_response为空的未答复问题总数

错误原因

  • 原查询用term匹配字符串[ ],ES中空数组属于数组类型,和[ ]字符串不属于同一数据类型,无法匹配到任何结果
  • 原查询未覆盖user_response字段不存在的统计场景

正确查询语句

你可以直接使用以下查询获取符合要求的统计结果:

GET /activity_tracking/_search
{
  "size": 0,
  "query": {
    "bool": {
      "must_not": [
        {
          "exists": {
            "field": "user_response.qid"
          }
        }
      ]
    }
  },
  "aggs": {
    "unreplied_count": {
      "value_count": {
        "field": "_id"
      }
    }
  }
}

返回结果里aggregations.unreplied_count.value就是你需要的未答复问题总数量。

查询原理

根据你提供的mapping,user_response是object类型,字段下包含子字段qid:

  • 如果user_response字段不存在,user_response.qid的exists查询结果为false
  • 如果user_response是空数组,数组内没有任何对象,user_response.qid也不会被索引,exists查询结果同样为false
    所以以上查询可以同时覆盖两种统计场景。

如果需要明确拆分两种场景的逻辑,也可以使用以下写法:

GET /activity_tracking/_search
{
  "size": 0,
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must_not": [
              {
                "exists": {
                  "field": "user_response"
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "exists": {
                  "field": "user_response"
                }
              }
            ],
            "must_not": [
              {
                "exists": {
                  "field": "user_response.qid"
                }
              }
            ]
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:09:03