官方文档链接
Elastic search 可以使用 aggregations 功能对查询的数据进行聚合,支持多重聚合。
下面举一个计数聚合的例子:
{
"query":{
"bool":{
"must":[
{
"range":{
"@timestamp":{
"gte":1536805052000,
"lte":1536905052000,
"format":"epoch_millis"
}
}
}
]
}
},
"size":0,
"stored_fields":[],
"script_fields":{},
"docvalue_fields":[],
"aggs":{
"results_by_component":{
"terms":{
"field":"component_name",
"size":5
}
}
}
}
其中, query字段描述查询条件,这个例子中,我们只对时间做了限制,查询指定时间段内的所有log。
"size"为 0 表示显示 0 条查询结果, 在这里我们对每一条查询结果不感兴趣,只对聚合结果感兴趣,所以将size设置为 0。
接下来 "aggs"字段是对聚合的设置。这个例子比较简单,只对查询结果按 "component_name"进行聚合( “component_name” 是定义在每条log中的一个字段,表示这条log是由哪个component产生)。
通过上面的query,我们得到了如下结果(结果只截取 aggregations 部分):
{
"aggregations": {
"results_by_component": {
"doc_count_error_upper_bound": 120532,
"sum_other_doc_count": 4539368,
"buckets": [
{
"key": "component_test01",
"doc_count": 1762831
},
{
"key": "component_test02",
"doc_count": 1680588
},
{
"key": "component_test03",
"doc_count": 1304537
},
{
"key": "component_test04",
"doc_count": 970381
},
{
"key": "component_test05",
"doc_count": 835906
}
]
}
}
下面举一个百分位数聚合的例子。
query内容不变,我们将 "aggs"的内容做如下修改:
{
"aggs": {
"percentile_time":{
"percentiles":{
"field":"response_time_ms",
"percents":[
50,
90,
95,
99,
99.9
]
}
}
}
}
统计"response_time_ms"的百分位数,将得到如下结果:
{
"aggregations": {
"percentile_time": {
"values": {
"50.0": 18.151901586137335,
"90.0": 97.01449517757428,
"95.0": 297.5137181184368,
"99.0": 1079.8195648476355,
"99.9": 5414.805508330881
}
}
}
}
如果想得到每一个 component_name 下对"response_status"计数聚合和 "response_time_ms"的百分位数聚合,则可嵌套多个聚合条件
例子
{
"aggregations": {
"results_by_component":{
"terms":{
"field":"component_name",
"size":5
},
"aggs":{
"status_code_count":{
"terms":{
"field":"response_status",
"size":5
}
},
"percentile_time":{
"percentiles":{
"field":"response_time_ms",
"percents":[
50,
90,
95,
99,
99.9
]
}
}
}
}
}
}
聚合结果如下:
{
"aggregations": {
"results_by_component": {
"doc_count_error_upper_bound": 137336,
"sum_other_doc_count": 7650192,
"buckets": [
{
"key": "component_test01",
"doc_count": 1762831,
"percentile_time": {
"values": {
"50.0": 79.41854086887764,
"90.0": 393.42530776763,
"95.0": 423.8467834610685,
"99.0": 1100.6490415600176,
"99.9": 8980.100018441459
}
},
"status_code_count": {
"doc_count_error_upper_bound": 20,
"sum_other_doc_count": 88619,
"buckets": [
{
"key": 200,
"doc_count": 1343600
},
{
"key": 201,
"doc_count": 282345
},
{
"key": 400,
"doc_count": 48267
}
]
}
},
{
"key": "component_test02",
"doc_count": 1680588,
"percentile_time": {
"values": {
"50.0": 47.20412905186976,
"90.0": 98.34655431504568,
"95.0": 379.85813836814305,
"99.0": 1049.5351664550062,
"99.9": 8602.25736085292
}
},
"status_code_count": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 74103,
"buckets": [
{
"key": 200,
"doc_count": 1279955
},
{
"key": 201,
"doc_count": 282159
},
{
"key": 400,
"doc_count": 44371
}
]
}
}
]
}
}
}