聚合查询案例
- 计算每个tag下的商品数量
GET /ecommerce/product/_search
{
"aggs": {
"group_by_tags": {
"terms": { "field": "tags" }
}
}
}
- 对名称中包含yagao的商品,计算每个tag下的商品数量
GET /ecommerce/product/_search
{
"size": 0,
"query": {
"match": {
"name": "yagao"
}
},
"aggs": {
"all_tags": {
"terms": {
"field": "tags"
}
}
}
}
- 先分组,再算每组的平均值,计算每个tag下的商品的平均价格
GET /ecommerce/product/_search
{
"size": 0,
"aggs" : {
"group_by_tags" : {
"terms" : { "field" : "tags" },
"aggs" : {
"avg_price" : {
"avg" : { "field" : "price" }
}
}
}
}
}
- 计算每个tag下的商品的平均价格,并且按照平均价格降序排序
{
"size": 0,
"aggs" : {
"all_tags" : {
"terms" : { "field" : "tags", "order": { "avg_price": "desc" } },
"aggs" : {
"avg_price" : {
"avg" : { "field" : "price" }
}
}
}
}
}
- 问题及解决方案
1. elasticsearch 使用聚合查询操作,需要设置fielddata 为true,否则报错如下
解决方案:
elasticsearch 5.x 与 elasticsearch 7.x 在设置时有所不同,7版本废除了type
elasticsearch 5.x 设置方法:
PUT /ecommerce/_mapping/product
{
"properties": {
"tags": {
"type": "text",
"fielddata": true
}
}
}
elasticsearch 7.x 设置方法:
PUT /ecommerce/_mapping
{
"properties": {
"tags": {
"type": "text",
"fielddata": true
}
}
}