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

Elasticsearch查询:统计images数组长度≥2的文档数量及对应ID

Elasticsearch 查询数组字段长度≥2的文档

1. 查询符合条件的书籍数量

用count API结合脚本判断images数组元素数量,直接返回统计结果:

GET /index_book_1/_count
{
  "query": {
    "bool": {
      "filter": {
        "script": {
          "script": "doc['images'].size() >= 2"
        }
      }
    }
  }
}

返回结果里的count字段就是符合条件的书籍总数(示例中应为2)。

2. 查询所有符合条件的书籍ID

用search API筛选目标文档,同时关闭_source返回,只获取文档ID提升效率:

GET /index_book_1/_search
{
  "query": {
    "bool": {
      "filter": {
        "script": {
          "script": "doc['images'].size() >= 2"
        }
      }
    },
    "_source": false,
    "fields": []
  }
}

返回结果的hits.hits数组中,每个元素的_id字段就是符合条件的书籍ID(示例中为1234、1235)。

性能优化方案(可选)

如果需要频繁查询数组长度,建议给索引添加一个运行时字段存储数组长度,后续查询用普通范围过滤更高效:

PUT /index_book_1/_mapping
{
  "runtime": {
    "images_count": {
      "type": "long",
      "script": "emit(doc['images'].size())"
    }
  }
}

之后的查询可以简化为:

# 统计数量
GET /index_book_1/_count
{
  "query": {
    "range": {
      "images_count": {
        "gte": 2
      }
    }
  }
}

# 获取ID
GET /index_book_1/_search
{
  "query": {
    "range": {
      "images_count": {
        "gte": 2
      }
    },
    "_source": false,
    "fields": []
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:20:29