爲了描述ES是如何進行嵌套聚合、下鑽分析,聚合分析。下面經過五個業務需求來進行描述。數組
因爲tag是一個數組,因此其實統計的就是針對tag數組中的每一個值,全部文檔中tag字段中包含這個值的文檔數量。code
GET /product/_search { "size": 0, "aggs": { "all_tags": { "terms": { "field": "tags", "size": 10 } } } } { "took" : 0, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : { "value" : 3, "relation" : "eq" }, "max_score" : null, "hits" : [ ] }, "aggregations" : { "all_tags" : { "doc_count_error_upper_bound" : 0, "sum_other_doc_count" : 0, "buckets" : [ { "key" : "fangzhu", "doc_count" : 2 }, { "key" : "meibai", "doc_count" : 1 }, { "key" : "qingxin", "doc_count" : 1 } ] } } }
GET /product/_search { "query": { "match": { "name": "yagao" } }, "size": 0, "aggs": { "all_tags": { "terms": { "field": "tags", "size": 10 } } } }
GET /product/_search { "size": 0, "aggs": { "group_by_tags": { "terms": { "field": "tags", "size": 10 }, "aggs": { "avg_price": { "avg": { "field": "price" } } } } } }
GET /product/_search { "size": 0, "aggs": { "group_by_tags": { "terms": { "field": "tags", "size": 10, "order": { "avg_price": "desc" } }, "aggs": { "avg_price": { "avg": { "field": "price" } } } } } }
GET /product/_search { "size": 0, "aggs": { "group_by_price": { "range": { "field": "price", "ranges": [ { "from": 0, "to": 20 }, { "from": 20, "to": 40 }, { "from": 40, "to": 50 } ] }, "aggs": { "group_by_tags": { "terms": { "field": "tags", "size": 10 }, "aggs": { "avg_price": { "avg": { "field": "price" } } } } } } } }