概述
继续跟中华石杉老师学习ES,第41篇
课程地址: https://www.roncoo.com/view/55
案例
需求: 统计价格大于2000的电视的平均价格
原始数据:
不多说了,很简单,只需要在查询的时候过滤下即可
GET /tvs/sales/_search { "query": { "range": { "price": { "gte": "2000" } } }, "aggs": { "avg_price": { "avg": { "field": "price" } } }, "size": 0 }
返回结果:
{ "took": 7, "timed_out": false, "_shards": { "total": 5, "successful": 5, "skipped": 0, "failed": 0 }, "hits": { "total": 5, "max_score": 0, "hits": [] }, "aggregations": { "avg_price": { "value": 3500 } } }
我们把原始数据也返回(去掉 "size": 0
),来校验下,是否正确。
GET /tvs/sales/_search { "query": { "range": { "price": { "gte": "2000" } } }, "aggs": { "avg_price": { "avg": { "field": "price" } } } }
返回:
{ "took": 27, "timed_out": false, "_shards": { "total": 5, "successful": 5, "skipped": 0, "failed": 0 }, "hits": { "total": 5, "max_score": 1, "hits": [ { "_index": "tvs", "_type": "sales", "_id": "QzGrtGwBCp8vhw_gCmb9", "_score": 1, "_source": { "price": 2000, "color": "红色", "brand": "长虹", "sold_date": "2016-11-05" } }, { "_index": "tvs", "_type": "sales", "_id": "PzGrtGwBCp8vhw_gCmb9", "_score": 1, "_source": { "price": 2000, "color": "红色", "brand": "长虹", "sold_date": "2016-11-05" } }, { "_index": "tvs", "_type": "sales", "_id": "QDGrtGwBCp8vhw_gCmb9", "_score": 1, "_source": { "price": 3000, "color": "绿色", "brand": "小米", "sold_date": "2016-05-18" } }, { "_index": "tvs", "_type": "sales", "_id": "RDGrtGwBCp8vhw_gCmb9", "_score": 1, "_source": { "price": 8000, "color": "红色", "brand": "三星", "sold_date": "2017-01-01" } }, { "_index": "tvs", "_type": "sales", "_id": "RTGrtGwBCp8vhw_gCmb9", "_score": 1, "_source": { "price": 2500, "color": "蓝色", "brand": "小米", "sold_date": "2017-02-12" } } ] }, "aggregations": { "avg_price": { "value": 3500 } } }
比对下原始数据,可知正确。