写在前面的话:
1)本系列主要针对es7.3版本的聚合操作,目的不是翻译文档,而是通过实例来熟悉文档上的聚合API,旨在更好的理解es的聚合,所有代码都在es7.3运行通过。
2)本系列主要针对有一定es经验的工程师,所以对一些简单的操作细节不会赘述,望理解。
3) 本文用的测试的索引数据为kibana自带的kibana_sample_data_ecommerce数据,可以直接从kibana7.3导入
聚合操作的对象可以分为索引中已经存在的field和通过script计算的值
avg aggregaions
field实例
对taxful_total_price进行聚合
POST /kibana_sample_data_ecommerce/_search
{
"size": 0,
"aggs":{
"avg_price":{
"avg": {
"field": "taxful_total_price"
}
}
}
}
script实例
找出所有购买物品的平均单价
POST /kibana_sample_data_ecommerce/_search
{
"size": 0,
"aggs" : {
"avg_price_sum" : {
"avg" : {
"script" : {
"source" : "doc.taxful_total_price.value/doc.total_quantity.value"
}
}
}
}
}
value script实例
总价格提升20%后的平均值
POST /kibana_sample_data_ecommerce/_search
{
"size": 0,
"aggs" : {
"avg_corrected_price" : {
"avg" : {
"field" : "taxful_total_price",
"script" : {
"lang": "painless",
"source": "_value * params.correction",
"params" : {
"correction" : 1.2
}
}
}
}
}
}
missing value
对缺失的值taxful_total_price按照默认100处理
POST /kibana_sample_data_ecommerce/_search
{
"size": 0,
"aggs": {
"avg_price": {
"avg": {
"field": "taxful_total_price",
"missing": 100
}
}
}
}
Weighted Avg Aggregation
加权平均值
以taxful_total_price为value,以total_quantity为weight,进行加权求平均
POST /kibana_sample_data_ecommerce/_search
{
"size": 0,
"aggs": {
"avg_weight_price": {
"weighted_avg": {
"value": {
"field": "taxful_total_price"
},
"weight": {
"field": "total_quantity"
}
}
}
}
}
value可以为列表,权重只能为单个值
#导入数据
PUT /test_weighted_avg/_bulk
{ "index": {}}
{"value":[1,2,4],"weight":5}
{ "index": {}}
{"value":[2,3],"weight":8}
#求加权平均值
POST /test_weighted_avg/_search
{
"size": 0,
"aggs": {
"avg_weight": {
"weighted_avg": {
"value": {
"field": "value"
},
"weight": {
"field": "weight"
}
}
}
}
}
script 实例
#导入数据
PUT /test_weighted_avg/_bulk
{ "index": {}}
{"value":[1,2,4],"weight":5}
{ "index": {}}
{"value":[2,3],"weight":8}
#通过script求加权平均值
POST /test_weighted_avg/_search
{
"size": 0,
"aggs" : {
"weighted_grade": {
"weighted_avg": {
"value": {
"script": "doc.value.value + 1"
},
"weight": {
"script": "doc.weight.value + 1"
}
}
}
}
}
missing
1)通过missing貌似可以使用不存在的域,来增加自己想要的weight的效果(此时的权重为全局统一)
比如以下通过missing,给了一个2的权重
PUT /test_weighted_avg2/_bulk
{ "index": {}}
{"value":[1,2,4]}
{ "index": {}}
{"value":[2,3]}
POST /test_weighted_avg2/_search
{
"size": 0,
"aggs": {
"avg_weight": {
"weighted_avg": {
"value": {
"field": "value"
},
"weight": {
"field": "weight",
"missing":2
}
}
}
}
}
2)普通的用法
如果taxful_total_price缺失,则使用默认值100,如果total_quantity缺失,则使用默认值2
POST /kibana_sample_data_ecommerce/_search
{
"size": 0,
"aggs": {
"avg_weight_price": {
"weighted_avg": {
"value": {
"field": "taxful_total_price",
"missing":100
},
"weight": {
"field": "total_quantity",
"missing":2
}
}
}
}
}
网友评论