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
相关产品推荐
相关产品推荐

