LoginSignup
0

More than 5 years have passed since last update.

Elasticsearchのaggregationsのサンプル

Posted at

あるtypeの月ごとの件数をカウントする必要があり、
頑張って調べたのでメモ。

リクエストのサンプル

GET index_name/type_name/_search
{
  "size": 0, 
  "query": {
    "filtered": {
      "filter": {
        "range": {
          "{{ sample_time }}": {
            "gte": xxxxxxxxxxx
          }
        }
      }
    }
  },
  "aggs": {
    "{{ monthly_count }}": {
      "date_histogram": {
        "field": "{{ sample_time }}",
        "interval": "month",
        "time_zone": "+9:00",
        "order": {
          "_key": "desc"
        }
      }
    }
  }
}
  • sizeは、条件にヒットするドキュメントが出力されるのが邪魔なので0にした
  • queryで集計するドキュメントの条件を絞れる(例はsample_timeがある日付以降)
  • aggsからが集計の条件

aggsの各パラメータの意味

"aggs": {
    "{{ 適当な名前をつける }}": {
      "date_histogram": {             # date_histgramを指定すると日付の間隔でbucketを作れるらしい
        "field": "{{ sample_time }}", # 集計するキーとなるフィールド
        "interval": "month",          # 月ごとに集計したいのでmonth
        "time_zone": "+9:00",         # タイムゾーンを調整できる(utcだったので+9時間した)
        "order": {
          "_key": "desc"              # 集計結果をソート可能
        }
      }
    }
}

レスポンスのサンプル

{
   "took": xxx,
   "timed_out": false,
   "_shards": {
      "total": xxx,
      "successful": xxx,
      "failed": 0
   },
   "hits": {
      "total": xxx,
      "max_score": 0,
      "hits": []
   },
   "aggregations": {
      "{{ 適当につけた名前 }}": {
         "buckets": [
            {
               "key": 1522540800,  # 降順で月ごとの件数が集計された
               "doc_count": 300    # 対象月の件数
            },
            {
               "key": 1519862400,
               "doc_count": 400
            },
            {
               "key": 1517443200,
               "doc_count": 100
            }
         ]
      }
   }
}
  • 例は2018/02 ~ 2018/04の月ごとの集計結果、件数は適当です

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0