13.ES|Aggregations(Bucket/Metrics)

Aggregation

集計する機能。SQLで言うところの、GROUP BY。
sumやmaxといった集約を行える。

集約クエリ(Aggregations)は、BucketとMetricsに分かれる。

  • Bucket」…検索結果を指定条件で分類。(例)検索結果を期間ごとにグループ化するなど。
  • 「Metrics」…Bucketのデータを集計。(例)合計値を求める(sum)・最大値を求める(max)など。

  • Elasticsearch公式/「集約の実行」 www.elastic.co

Bucket

  • サンプルクエリ
GET /_search
{
    "aggs" : {
        "genres" : {
            "terms" : { "field" : "genre" } 
        }
    }
}
  • レスポンス
{
    ...
    "aggregations" : {
        "genres" : {
            "doc_count_error_upper_bound": 0, 
            "sum_other_doc_count": 0, 
            "buckets" : [ 
                {
                    "key" : "electronic",
                    "doc_count" : 6
                },
                {
                    "key" : "rock",
                    "doc_count" : 3
                },
                {
                    "key" : "jazz",
                    "doc_count" : 2
                }
            ]
        }
    }
}

Metrics

※Metic(メトリック)とは、コンピュータネットワークにおける通信相手までのパス(経路)の距離のこと。

The aggregations in this family compute metrics based on values extracted in one way or another from the documents that are being aggregated. The values are typically extracted from the fields of the document (using the field data), but can also be generated using scripts.

  • Elasticsearch公式/「Metrics Aggregations」 www.elastic.co

  • サンプルクエリ

PUT metrics_index/_doc/1
{
  "network.name" : "net-1",
  "latency_histo" : {
      "values" : [0.1, 0.2, 0.3, 0.4, 0.5], 
      "counts" : [3, 7, 23, 12, 6] 
   }
}

PUT metrics_index/_doc/2
{
  "network.name" : "net-2",
  "latency_histo" : {
      "values" :  [0.1, 0.2, 0.3, 0.4, 0.5], 
      "counts" : [8, 17, 8, 7, 6] 
   }
}

POST /metrics_index/_search?size=0
{
    "aggs" : {
        "total_latency" : { "sum" : { "field" : "latency_histo" } }
    }
}
  • レスポンス
{
    ...
    "aggregations" : {
        "total_latency" : {
           "value" : 28.8
        }
    }
}