iT邦幫忙

第 12 屆 iT 邦幫忙鐵人賽

DAY 28
0
Elastic Stack on Cloud

Python&Elasticsearch 入門系列 第 28

IT鐵人第28天 Elasticsearch 使用python查詢資料 Aggregations:Sum/Value Count

今天文章的內容是Sum(總和)跟Value Count(數量計算)

今天的示範資料
https://ithelp.ithome.com.tw/upload/images/20201012/20129976F8cr51mt3U.png

Sum

Sum大家應該都很熟悉了,這邊就不多做解釋,直接進入範例吧

先定個目標,假設我想要統計出資工一2的英文分數總和
query:

"query": {
  "term": {
    "class": "資工一2"
  }
}

aggs query:

"aggs": {
  "sum_eng": {
    "sum": {
      "field": "grades.eng",
      "missing": 40
    }
  }
}

組合起來的query:

{
  "query": {
    "term": {
      "class": "資工一2"
    }
  },
  "aggs": {
    "sum_eng": {
      "sum": {
        "field": "grades.eng",
        "missing": 40
      }
    }
  }
}

結果:

"aggregations" : {
  "sum_eng" : {
    "value" : 212.0
  }
}

也可以用腳本調整,假設想幫分數低於60分的人+10分,範例如下
aggs query:

"aggs": {
  "sum_eng": {
    "sum": {
      "field": "grades.eng",
      "missing": 40, 
      "script": {
        "lang": "painless",
        "source": "if(doc['grades.eng'].value<60){doc['grades.eng'].value+10;}else{doc['grades.eng'].value;}"
      }
    }
  }
}

結果:

"aggregations" : {
  "sum_eng" : {
    "value" : 222.0
  }
}

還有另外一種是針對字段histogram fields的應用,想了解更多的可以去:
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-sum-aggregation.html#search-aggregations-metrics-sum-aggregation-histogram-fields
histogram fields說明:
https://www.elastic.co/guide/en/elasticsearch/reference/current/histogram.html

Value Count

這種聚合方式會回傳指定字段的統計數量

先定個目標,假設我們今天想知道資工一2的班級人數
query

"query": {
  "term": {
    "class": "資工一2"
  }
}

aggs query:

"aggs": {
  "class_count": {
    "value_count": {
      "field": "class"
    }
  }
}

組合起來的query:

{
  "query": {
    "term": {
      "class": "資工一2"
    }
  },
  "aggs": {
    "class_count": {
      "value_count": {
        "field": "class"
      }
    }
  }
}

結果:

"aggregations" : {
  "class_count" : {
    "value" : 3
  }
}

一樣有針對histogram fields的應用,想了解可以去:
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html

今天的文章就到這邊,謝謝大家


上一篇
IT鐵人第27天 Elasticsearch 使用python查詢資料 Aggregations:Percentiles/Percentile Ranks
下一篇
IT鐵人第29天 Elasticsearch 使用python查詢資料 Aggregations:Terms
系列文
Python&Elasticsearch 入門30

尚未有邦友留言

立即登入留言