1. 按照 tags 字段 进行分组
GET /ecommerce/product/_search
{ "size": 0, "aggs": { "group_by_tag": { "terms": { "field": "tags", "size": 10 } } }}(注意: "size": 0 的作用是不需要获得所有匹配的 document 的信息,只返回聚合的结果)
此时如果抛出了下面的错误:
"root_cause": [
{ "type": "illegal_argument_exception", "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [tags] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead." } ]需要对 tags 这个字段需要进行下面的处理
PUT /ecommerce/_mapping/product
{ "properties": { "tags": { "type": "text", "fielddata": true } }}
2. 对名称中包含yagao的商品,计算每个tag下的商品数量
GET /ecommerce/product/_search{ "size": 0, "query": { "match": { "name": "yagao" } }, "aggs": { "all_tags": { "terms": { "field": "tags" } } }}
3. 先分组,再算每组的平均值,计算每个tag下的商品的平均价格
GET /ecommerce/product/_search
{ "size": 0, "aggs" : { "group_by_tags" : { "terms" : { "field" : "tags" }, "aggs" : { "avg_price" : { "avg" : { "field" : "price" } } } } }}
4. 计算每个tag下的商品的平均价格,并且按照平均价格降序排序
GET /ecommerce/product/_search
{ "size": 0, "aggs" : { "all_tags" : { "terms" : { "field" : "tags", "order": { "avg_price": "desc" } }, "aggs" : { "avg_price" : { "avg" : { "field" : "price" } } } } }}
5. 按照指定的价格范围区间进行分组,然后在每组内再按照tag进行分组,最后再计算每组的平均价格
{
"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" }, "aggs": { "average_price": { "avg": { "field": "price" } } } } } } }}