1、查询的结果聚合:先执行查询,在查询结果的基础上聚合
GET how2java/product/_search //求价格大于1千的商品的价格平均值 { "size": 0, "query": { "range": { "price": { "gt": 10000 } } }, "aggs": { "avg_price": { "avg": { "field": "price" } } } }
结果:
{ "took": 3, "timed_out": false, "_shards": { "total": 5, "successful": 5, "skipped": 0, "failed": 0 }, "hits": { "total": 2072, "max_score": 0, "hits": [] }, "aggregations": { "avg_price": { "value": 26412.76833976834 } } }
基于查询结果的聚合 并在聚合中再次执行查询:两次查询的交集用于聚合
GET how2java/product/_search { "size": 0, "query": { //查询1 "range": { "price": { "gt": 10000 } } }, "aggs": { "avg_price": { "avg": { "field": "price" } }, "avg_price2": { "filter": { //查询2 "range": { "price": { "gt": 50000 } } }, "aggs": { "avg_price22": { //查询1和查询2的交集用于本次聚合
"avg": { "field": "price" } } } } } }
取消查询结果案例
GET how2java/product/_search { "size": 0, "query": { //查询1 "range": { "price": { "gt": 10000 } } }, "aggs": { "avg_price": { "avg": { "field": "price" } }, "avg_price2": { "global": {}, //查询1的查询结果不会作用于本次聚合
"aggs": { "avg_price22": { "avg": { "field": "price" } } } } } }
2、基于聚合结果的聚合: 二次聚合
GET how2java/product/_search //求每个地域下商品的平均价格 { "size": 0, "aggs": { "place_bucket": { //先按地域分桶 "terms": { "field": "place.keyword", "size": 100 }, "aggs": { //在地域桶的同级求平均价格 "avg_price": { "avg": { "field": "price" } } } } } }
3、基于聚合结果的查询:这个说法不准确,其实就是不想让查询的结果作用于聚合(查询和聚合各干各的)
GET how2java/product/_search //查询商品价格大于50000的数据,同时聚合所有商品的平均价格 { "post_filter": { //不同在于query查询时 query会基于查询结果聚合,而post_filter不影响聚合 "range": { "price": { "gt": 50000 } } }, "aggs": { "avg_price": { "avg": { "field": "price" } } } }
基于聚合结果的查询的用处比如如下场景
GET how2java/product/_search //查询每个地域商品的数量,并查询某个地域商品的详细信息 { "post_filter": { "term": { "place.keyword": "上海" } }, "aggs": { "place_bucket": { //按地域分桶 "terms": { "field": "place.keyword" } } } }
结果如下: 查询和聚合各干各的互不干扰
标签:基于,聚合,price,查询,field,aggs,avg From: https://www.cnblogs.com/wscw/p/16789991.html