Elasticsearch笔记:聚合查询之多字段查询分组
2.1 先分组, 再聚合统计
(1) 先按tags分组, 再计算每个tag下图书的平均价格, 请求语法:
GET book_shop / it_book / _search { "size": 0, "aggs": { "group_by_tags": { "terms": { "field": "tags.keyword" }, "aggs": { "avg_price": { "avg": { "field": "price" } } } } } }
(2) 响应结果:
{ "hits": { "total": 3, "max_score": 0.0, "hits": [] }, "aggregations": { "group_by_tags": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [{ "key": "Java", "doc_count": 3, "avg_price": { "value": 102.33333333333333 } }, { "key": "编程语言", "doc_count": 2, "avg_price": { "value": 114.0 } }, ...... ] } }
2.2 先分组, 再统计, 最后排序
(1) 计算每个tag下图书的平均价格, 再按平均价格降序排序, 查询语法:
GET book_shop / it_book / _search { "size": 0, "aggs": { "all_tags": { "terms": { "field": "tags.keyword", "order": { "avg_price": "desc" } // 根据下述统计的结果排序 }, "aggs": { "avg_price": { "avg": { "field": "price" } } } } } }
(2) 响应结果:
与#2.1节内容相似, 区别在于按照价格排序显示了.
2.3 先分组, 组内再分组, 然后统计、排序
(1) 先按价格区间分组, 组内再按tags分组, 计算每个tags组的平均价格, 查询语法:
GET book_shop/it_book/_search { "size": 0, "aggs": { "group_by_tags": { "terms": { "field": "tags.keyword" }, "aggs": { "avg_price": { "avg": { "field": "price" } } } } } }
(2) 响应结果:
{ "hits": { "total": 3, "max_score": 0.0, "hits": [] }, "aggregations": { "group_by_price": { "buckets": [{ "key": "0.0-100.0", // 区间0.0-100.0 "from": 0.0, "to": 100.0, "doc_count": 1, // 共查找到了3条文档 "group_by_tags": { // 对tags分组聚合 "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [{ "key": "Java", "doc_count": 1, "avg_price": { "value": 79.0 } }, ...... ] } }, { "key": "100.0-150.0", "from": 100.0, "to": 150.0, "doc_count": 2, "group_by_tags": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [{ "key": "Java", "doc_count": 2, "avg_price": { "value": 114.0 } }, ...... } ] } } ] } }