1
Elastic Stack on Cloud

# 4. avg:查出聚合的平均值

## 一般查詢聚合分析

``````POST /it_help/_search?size=0
{
"query": {
"filter": {
"match": { "name": "java" }//僅統計名中帶java
}
},
"aggs": {
"java_age_sum": {
"sum": {
"field": "age",//統計欄位為年齡
"miss": 18//若年齡值為空則以18來算
}
}
}
}
// 類似 sql :select sum(age) where name like %java%;
``````

## 然而聚合分析也支援腳本運算

``````POST /it_help/_search?size=0
{
"query": {
"constant_score": {
"filter": {
"term": { "name": "java" }
}
}
},
"aggs": {
"java_ageSum": {
"sum": {
"script": {
"source": "doc.age.value"
}
}
}
}
}
``````

# 5. Value Count :value計數，通常跟平均一起顯示，計算目標值計數，重複值也會算+1

``````POST /it_help/_search?size=0
{
"aggs" : {
"name_count" : { "value_count" : { "field" : "name" } }
}
}
//類似 select count(*) from it_help where name <> null
``````

# 6.stats:統計聚合

``````//直接貼個官網的
POST /exams /_search ? size = 0 {
"aggs": {
"stats": {
}
}
}
}
//return
{ ...
"aggregations": {
"count": 2,
"min": 50.0,
"max": 100.0,
"avg": 75.0,
"sum": 150.0
}
}
}
``````

# 7. Weighted Avg:加權平均數

## 關鍵公式: ∑(value * weight) / ∑(weight)

``````POST /exams/_doc?refresh //放入一筆資料
{
"weight": 2
}

POST /exams/_search
{
"size": 0,
"aggs": {
"weighted_avg": {//指定平均數
"value": {
},
"weight": {//指定加權平均權重
"field": "weight"
}
}
}
}
}

//返回
{
...
"aggregations": {
"value": 2.0 //=((1*2) + (2*2) + (3*2)) / (2+2+2) == 2
}
}
}
``````

# 8. cardinality:基數聚合:不計算重複值加總

``````//計算資料庫中有幾種性別
GET /it_help/_search {
"size": 0,
"aggs": {
"distinct_sex": {
"cardinality": {
"field": "sex"
}
}
}
}
//返回
"aggregations": {
"distinct_sex": {
"value": 2 //理所當然的吧，就是生理男跟生理女而已
}
}

``````

# 9. boxplot:箱型圖(盒鬚圖)聚合

``````GET it_help/_search
{
"size": 0,
"aggs": {
"age_boxplot": {
"boxplot": {
"field": "age"
}
}
}
}

//返回
{
"aggregations": {
"min": 18.0,
"max": 36.0,
"q1": 22.0,//下四分位數
"q2": 26.0,//中位數
"q3": 30.0//上四位數
}
}
}
``````

# 10.percentile:百分位數指標

...這還真是不知道該怎麼解釋，就是盒鬚圖的詳細版

``````//用法與箱型圖極為相似，因為資料不夠就直接拷官網的拉
GET latency/_search
{
"size": 0,
"aggs": {
"percentiles": {
}
}
}
}
//返回
{
"aggregations": {
"values": {
"1.0": 5.0,
"5.0": 25.0,
"25.0": 165.0,
"50.0": 445.0,
"75.0": 725.0,
"95.0": 945.0,
"99.0": 985.0
}
}
}
}
``````

(通常是很隨便的請列舉五個)