Elasticsearch学习之深入聚合分析三---案例实战
1. 统计指定品牌下每个颜色的销量
任何的聚合,都必须在搜索出来的结果数据中进行,搜索结果,就是聚合分析操作的scope
GET /tvs/sales/_search { "size": 0, "query": { "term": { "brand": { "value": "小米" } } }, "aggs": { "group_by_color": { "terms": { "field": "color" } } } }
2. 单个品牌与所有品牌销量对比
一个聚合操作,必须在query的搜索结果范围内执行出来两个结果,一个结果,是基于query搜索结果来聚合的; 一个结果,是对所有数据执行聚合的
GET /tvs/sales/_search { "size": 0, "query": { "term": { "brand": { "value": "长虹" } } }, "aggs": { "single_brand_avg_price": { "avg": { "field": "price" } }, "all": { "global": {}, "aggs": { "all_brand_avg_price": { "avg": { "field": "price" } } } } } }
global:就是global bucket,就是将所有数据纳入聚合的scope,而不管之前的query
3. 统计价格大于1200的电视平均价格
搜索+聚合,过滤+聚合
GET /tvs/sales/_search { "size": 0, "query": { "constant_score": { "filter": { "range": { "price": { "gte": 1200 } } } } }, "aggs": { "avg_price": { "avg": { "field": "price" } } } }
4. 统计电视品牌最近一个月的销量
GET /tvs/sales/_search { "size": 0, "query": { "term": { "brand": { "value": "长虹" } } }, "aggs": { "recent_150d": { "filter": { "range": { "sold_date": { "gte": "now-150d" } } }, "aggs": { "recent_150d_avg_price": { "avg": { "field": "price" } } } }, "recent_140d": { "filter": { "range": { "sold_date": { "gte": "now-140d" } } }, "aggs": { "recent_140d_avg_price": { "avg": { "field": "price" } } } }, "recent_130d": { "filter": { "range": { "sold_date": { "gte": "now-130d" } } }, "aggs": { "recent_130d_avg_price": { "avg": { "field": "price" } } } } } }
aggs.filter,针对的是聚合去做的,如果放query里面的filter,是全局的,会对所有的数据都有影响
但是,如果,比如说你要统计长虹电视最近1个月的平均值; 最近3个月的平均值; 最近6个月的平均值
bucket filter:就是对不同的bucket下的aggs,进行filter
5. 统计每个颜色的电视的销售额,按照销售额降序排序
GET /tvs/sales/_search { "size": 0, "aggs": { "group_by_color": { "terms": { "field": "color", "order": { "avg_price": "asc" } }, "aggs": { "avg_price": { "avg": { "field": "price" } } } } } }
类似引用其他变量,本例中就是引用aggs中统计的每个颜色电视的平均价格
6. 颜色+品牌下钻分析时按最深层metric进行排序
GET /tvs/sales/_search { "size": 0, "aggs": { "group_by_color": { "terms": { "field": "color" }, "aggs": { "group_by_brand": { "terms": { "field": "brand", "order": { "avg_price": "desc" } }, "aggs": { "avg_price": { "avg": { "field": "price" } } } } } } } }
按照每种颜色下的每种品牌的平均价格进行降序排列