一、設置fielddata
PUT /index/_mapping/type
{
"properties":{
"fieldName":{
"type":"text",
"fielddata":true
}
}
}
例如:
PUT /ecommerce/_mapping/product
{
"properties": {
"tags":{
"type": "text",
"fielddata": true
}
}
}
二、聚合分析
1、聚合分析基本語法:
需求1:計算每個tag下的商品數量
GET /ecommerce/product/_search // GET /index/type/_search
{
"size": 0, // 返回數據hits內不顯示命中的數據記錄
"aggs": {
"all_tags": { // 聚合器名稱
"AGG_TYPE": { //AGG_TYPE聚合類型:terms,avg
"field": "fieldName"//字段名稱
}
}
}
}
2、為聚合分析添加刷選條件
需求2:對名稱中包含yagao的商品,計算每個tag下的商品數量GET /ecommerce/product/_search
{
"size": 0,
"query": {
"match": {
"name": "yaogao"
}
},
"aggs": {
"all_tags": {
"terms": {
"field": "tags"
}
}
}
}
3、嵌套聚合分析
需求3:先分組,再算每組的平均值,計算每個tag下的商品的平均價格GET /ecommerce/product/_search
{
"size": 0,
"aggs": {
"group_by_tags": {
"terms": {
"field": "tags"
},
"aggs": {
"avg_price": {
"avg": {
"field": "price"
}
}
}
}
}
}
4、聚合結果排序
需求4:計算每個tag下的商品的平均價格,並且按照平均價格降序排序
GET /ecommerce/product/_search
{
"size": 0,
"aggs": {
"all_tags": {
"terms": {
"field": "tags",
"order": {
"avg_price": "asc"
}
},
"aggs": {
"avg_price": {
"avg": {
"field": "price"
}
}
}
}
}
}需求5:按照指定的價格范圍區間進行分組,然后在每組內再按照tag進行分組,最后再計算每組的平均價格
GET /ecommerce/product/_search
{
"size": 0,
"aggs": {
"group_by_price": {
"range": {
"field": "price",
"ranges": [
{
"from": 0,
"to": 20
},{
"from": 20,
"to": 40
},{
"from": 40,
"to": 50
}
]
},
"aggs": {
"all_tags": {
"terms": {
"field": "price"
},
"aggs": {
"avg_price": {
"avg": {
"field": "price"
}
}
}
}
}
}
}
}