【Elasticsearch学习】之指标聚合(Metrics Aggregation)

Elasticsearch提供了几类聚合分析方法,分别为Bucketing Aggregation分桶聚合、Metrics Aggregation指标聚合,Matrix Aggregation矩阵聚合,Pipleline Aggregation管道聚合。

1.Metrics Aggregations(指标聚合)

  计算一个文档集合的某些指标。

  1)Avg,单值指标聚合,用于计算从文档中提取的值的平均值,计算值可以从文档中数值类型字段提取,也可以通过脚本生成。   

POST /kibana_sample_data_ecommerce/_search?size=0
{
    "aggs" : {
        "avg_price" : { "avg" : { "field" : "taxful_total_price" } }
    }
}

使用脚本:

POST /kibana_sample_data_ecommerce/_search?size=0
{
 "aggs" : {
        "avg_corrected_grade" : {
            "avg" : {
                "field" : "taxful_total_price",
                "script" : {
                    "lang": "painless",
                    "source": "_value * params.correction",
                    "params" : {
                        "correction" : 1.2
                    }
                }
            }
        }
    }
}

当计算的字段的值缺失时可以使用missing参数设置默认补充值。

  2)Weighted Avg Aggregations 加权平均值,用于计算从文档中提取的值的加权平均值。

    计算公式: ∑(value * weight) / ∑(weight)

    weighted_avg参数:

    value:提供计算值的字段配置或者脚本。value的参数:field-提取值的字段,missing-配置缺失值的默认值。

    weight:提供权重的字段配置或者脚本。weight的参数:field-提供权重的字段,missing-配置缺失值的默认值。

    format:返回的数值的格式。

    value_type:关于纯脚本和未映射的字段的提示。

POST /kibana_sample_data_ecommerce/_search
{
    "size": 0,
    "aggs" : {
        "weighted_grade": {
            "weighted_avg": {
                "value": {
                    "field": "taxful_total_price"
                },
                "weight": {
                    "field": "total_quantity"
                }
            }
        }
    }
}

  3)Cardinality Aggregations 计算某个字段不同值的近似数量。是一个近似算法,采用HyperLogLog++算法。

POST /kibana_sample_data_ecommerce/_search?size=0
{
    "aggs" : {
        "type_count" : {
            "cardinality" : {
                "field" : "day_of_week" //计算有多少个不同的day_of_week字段值
            }
        }
    }
}

  因为是近视计算所以存在精度问题,Cadinality提供了precision_threshold参数用来控制精度,采用以内存交换精度的方式,当精度越高使用的内存就越多。precision_threshold定义了一个数值,在计算的字段不同值的数量低于precision_threshold时,计算值是接近于准确的;如果数量高于时,精度将会下降。precision_threshold最大支持40000,默认为3000。

  3)Max、Min Aggregation 单指标,返回聚合文档中某个数值字段的最大值、最小值。当计算值大于2^53时,结果可能时近似的。

POST /kibana_sample_data_ecommerce/_search?size=0
{
    "aggs" : {
        "max_price" : { "max" : { "field" : "taxful_total_price" } }
    }
}
POST /kibana_sample_data_ecommerce/_search?size=0
{
    "aggs" : {
        "min_price" : { "min" : { "field" : "taxful_total_price" } }
    }
}

  4)Sum Aggregation 单指标,将从聚合文档中提取的数值进行求和。

POST /kibana_sample_data_ecommerce/_search?size=0
{
    "aggs" : {
        "sum_prices" : { "sum" : { "field" : "taxful_total_price" } }
    }
}

  5)Value Count Aggregation  单指标,计算文档的个数。

POST /kibana_sample_data_ecommerce/_search?size=0
{
    "aggs" : {
        "types_count" : { "value_count" : { "field" : "day_of_week" } }
    }
}

  返回:

"aggregations" : {
    "types_count" : {
      "value" : 4675
    }
  }

  6)Stats Aggregation 多值指标,输出多个统计结果,统计指标由:min,max,sum,count,avg组成。

POST /kibana_sample_data_ecommerce/_search?size=0
{
    "aggs" : {
        "price_stats" : { "stats" : { "field" : "taxful_total_price" } }
    }
}

  返回的统计结果:

"aggregations" : {
    "price_stats" : {
      "count" : 4675,
      "min" : 6.98828125,
      "max" : 2250.0,
      "avg" : 75.05542864304813,
      "sum" : 350884.12890625
    }
  }  

 7)Extended Stats Aggregation 多值指标,扩展stats的统计值,扩展的了例如sum_of_squares,variance,std_deviation,std_deviation_bound。

POST /kibana_sample_data_ecommerce/_search?size=0
{
    "aggs" : {
        "price_stats" : { "extended_stats" : { "field" : "taxful_total_price" } }
    }
}

  返回的统计结果:

"aggregations" : {
    "price_stats" : {
      "count" : 4675,
      "min" : 6.98828125,
      "max" : 2250.0,
      "avg" : 75.05542864304813,
      "sum" : 350884.12890625,
      "sum_of_squares" : 3.9367749294174194E7,//平方和
      "variance" : 2787.59157113862, //方差
      "std_deviation" : 52.79764740155209, // 标准差
      "std_deviation_bounds" : {
        "upper" : 180.6507234461523,   //可信区间上限
        "lower" : -30.53986616005605   //可信区间下限
      }
    }
  }

  默认情况下,extended_stats会返回标准差的置信区间,如果需要使用不同的区间,则可以定义sigma参数。

  8)String Stats Aggregation 多值指标,用于统计string类型的值。

    string stats aggregation统计的指标:

    count:非空字段的数量

    min_length:最短的长度

    max_length:最长的长度

    avg_length:平均长度

    entropy:计算所有字符串的信息熵,信息熵量化了字段包含的信息量,用于确定数据集的属性,如多样性、相似性、随机型。

POST /kibana_sample_data_ecommerce/_search?size=0
{
    "aggs" : {
        "message_stats" : { "string_stats" : { "field" : "customer_last_name.keyword" } }
    }
}
"aggregations" : {
    "message_stats" : {
      "count" : 4675,
      "min_length" : 3,
      "max_length" : 10,
      "avg_length" : 6.134545454545455,
      "entropy" : 4.688464053505158
    }
  }

  show_distribution参数:查看所有字符的概率分布。设置 "show_distribution": true即可查看。

   9)Top Hits Aggregation 用于跟踪聚合文档中匹配度最高的文档,是一个子聚合。top_hits聚合器通过bucket聚合器按某个字段结果集高效的进行分组,可以设置一个或多个bucket聚合器来决定结果应该被划分到哪一个分组中。

   参数:

  from:从何处开始抓取结果

  size:每个桶中最大的匹配数量,默认返回前三个。

  sort:排序。默认根据主查询的评分来排序。

POST /kibana_sample_data_ecommerce/_search?size=0
{
    "aggs": {
        "top_tags": {
            "terms": {
                "field": "day_of_week", //按照day_of_week进行分组
                "size": 2        //总共取3个分组
            },
            "aggs": {
                "top_price_hits": {
                    "top_hits": {
                        "sort": [
                            {
                                "taxful_total_price": { //按照taxful_total_price 降序排列
                                    "order": "desc"
                                }
                            }
                        ],
                        "_source": {
                            "includes": [ "day_of_week", "customer_full_name" ,"taxful_total_price"] //返回的字段
                        },
                        "size" : 1 //每个分组中取几个文档
                    }
                }
            }
        }
    }
}

  返回:

"aggregations" : {
    "top_tags" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 3130,
      "buckets" : [
        {
          "key" : "Thursday", //分桶的key值
          "doc_count" : 775, //分桶中的文档数量
          "top_price_hits" : {
            "hits" : {
              "total" : {
                "value" : 775,
                "relation" : "eq"
              },
              "max_score" : null,
              "hits" : [
                {
                  "_index" : "kibana_sample_data_ecommerce",
                  "_type" : "_doc",
                  "_id" : "CH-j7XEB-r_IFm6PJzGx",
                  "_score" : null,
                  "_source" : {
                    "customer_full_name" : "Eddie Lambert", 
                    "day_of_week" : "Thursday",
                    "taxful_total_price" : 369.96
                  },
                  "sort" : [
                    370.0
                  ]
                }
              ]
            }
          }
        },
        {
          "key" : "Friday",
          "doc_count" : 770,
          "top_sales_hits" : {
            "hits" : {
              "total" : {
                "value" : 770,
                "relation" : "eq"
              },
              "max_score" : null,
              "hits" : [
                {
                  "_index" : "kibana_sample_data_ecommerce",
                  "_type" : "_doc",
                  "_id" : "I3-j7XEB-r_IFm6PJjB6",
                  "_score" : null,
                  "_source" : {
                    "customer_full_name" : "Sultan Al Bryan",
                    "day_of_week" : "Friday",
                    "taxful_total_price" : 392.96
                  },
                  "sort" : [
                    393.0
                  ]
                }
              ]
            }
          }
        }
      ]
    }
  }  

  10)Geo Bound Aggregation ,计算包含所有地理值的矩形范围。

PUT /museums
{
    "mappings": {
        "properties": {
            "location": {
                "type": "geo_point"
            }
        }
    }
}


POST /museums/_bulk?refresh
{"index":{"_id":1}}
{"location": "52.374081,4.912350", "name": "NEMO Science Museum"}
{"index":{"_id":2}}
{"location": "52.369219,4.901618", "name": "Museum Het Rembrandthuis"}
{"index":{"_id":3}}
{"location": "52.371667,4.914722", "name": "Nederlands Scheepvaartmuseum"}
{"index":{"_id":4}}
{"location": "51.222900,4.405200", "name": "Letterenhuis"}
{"index":{"_id":5}}
{"location": "48.861111,2.336389", "name": "Musée du Louvre"}
{"index":{"_id":6}}
{"location": "48.860000,2.327000", "name": "Musée d'Orsay"}


POST /museums/_search?size=0
{
    "query" : {
        "match" : { "name" : "musée" }
    },
    "aggs" : {
        "viewport" : {
            "geo_bounds" : {
                "field" : "location",   //用于获取范围的字段
                "wrap_longitude" : true  //是否允许边界和国际日期线重叠
            }
        }
    }
}

  返回

"aggregations" : {
    "viewport" : {
      "bounds" : {
        "top_left" : {
          "lat" : 48.86111099738628, //纬度
          "lon" : 2.3269999679178  //经度
        },
        "bottom_right" : {
          "lat" : 48.85999997612089,
          "lon" : 2.3363889567553997
        }
      }
    }
  }

  11)Geo Centroid Aggregation,计算聚合文档的地理值的大概的中心点。

POST /museums/_search?size=0
{
    "aggs" : {
        "centroid" : {
            "geo_centroid" : {
                "field" : "location" 
            }
        }
    }
}

  返回中心点:

"aggregations" : {
    "centroid" : {
      "location" : {
        "lat" : 51.00982965203002,
        "lon" : 3.9662131341174245
      },
      "count" : 6
    }
  }

  12)Percentiles Aggregation,多值聚合,百分位聚合,用于计算文档中数值字段的一个或多个百分点。通常用于寻找异常值。

GET kibana_sample_data_ecommerce/_search
{
    "size": 0,
    "aggs" : {
        "quantity_time_outlier" : {
            "percentiles" : {
                "field" : "total_quantity" 
            }
        }
    }
}

  返回:  

"aggregations" : {
    "quantity_time_outlier" : {
      "values" : {
        "1.0" : 1.0, //1%的数量为 1
        "5.0" : 2.0, //5%的数量为 2
        "25.0" : 2.0,
        "50.0" : 2.0,
        "75.0" : 2.0,
        "95.0" : 4.0,
        "99.0" : 4.0
      }
    }
  }

  可使用percents指定想要计算的百分比。  

GET kibana_sample_data_ecommerce/_search
{
    "size": 0,
    "aggs" : {
        "quantity_time_outlier" : {
            "percentiles" : {
                "field" : "total_quantity",
                "percents" : [5, 80, 95] 
            }
        }
    }
}

  13)Percentile Ranks Aggregation 多值指标,百分比分级聚合,用于统计数值低于某个确定值的百分比数。

GET kibana_sample_data_ecommerce/_search
{
    "size": 0,
    "aggs" : {
        "quantity_time_ranks" : {
            "percentile_ranks" : {
                "field" : "total_quantity", 
                "values" : [3, 4]
            }
        }
    }
}

  返回:

"aggregations" : {
    "quantity_time_ranks" : {
      "values" : {
        "3.0" : 91.18716577540107,  //小于3的数量有91%多
        "4.0" : 99.78609625668449  //小于4的数量有99%多
      }
    }
  }

  14)Scripted Aggregation,通过脚本提供指标输出。

  脚本指标聚合通过执行4步进行:

  1.init_script:在提取文档集合前执行。运行设置任何的初始state。

  2.map_script:在每个文档被采集前执行一次。

  3.combine_script:当文档采集完毕后在每个分片上执行一次,可以合并从各个分片返回的state。

  4.reduce_script:当所有分片返回结果后,在协调节点上执行一次,提供对combine_script返回的state的访问。

  其他的参数:params,可以作为init_script、map_script、combine_script的参数

  脚本返回的对象或者存储在state中的对象只能是如下几种类型:原生ES类型、String、Map、Array。

举例:

PUT /transactions/_bulk?refresh
{"index":{"_id":1}}
{"type": "sale","amount": 80}
{"index":{"_id":2}}
{"type": "cost","amount": 10}
{"index":{"_id":3}}
{"type": "cost","amount": 30}
{"index":{"_id":4}}
{"type": "sale","amount": 130}

  init_script之前:state是空对象{}

  init_script在每个文档执行一次初始化操作,所以在每个分片上会有一个state副本:

  分片A :

  "state" : {
      "transactions" : []
  }
 分片B:
 
"state" : {
  
  "transactions" : []
}
 每个分片采集分片上的文档并在每个文档上执行map_script
 分片A上的state变为:
  "state" : {
      "transactions" : [ 80, -30 ]
  }
 分片B上的state变为:
  "state" : {
      "transactions" : [ -10, 130 ]
  }

  combine_script在每个分片采集文档完毕后执行,减少states中所有的transactions为一个总数,该总数被传回给coordinate节点。
 分片A:50 分片B:120
  
reduce_script接受一个包含combine script结果的数组,如"states" : [50,120],reduce_script将数组中的值相加得到最终返回的聚合值。
posted @ 2020-06-09 21:22  xiaohuoshan  阅读(591)  评论(0编辑  收藏  举报