2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Elasticsearchのaggregationを試す。

2
Last updated at Posted at 2018-08-10

Description

SQLで言うところの「group by」に相当するElasticsearchの「aggregation」機能を使ってみたので、それについてまとめた。

Environment

  • Elasticsearch: 6.3.2

Setup

今回はdocker環境のElasticsearchを使用し、公式のサンプルデータで試してみた。
これらについては以下の記事を参照。

Usage

aggregation機能はsearch apiに対して、「aggs」というキーの条件をつけると実行できる。
サンプルデータの場合、logstash-*インデックスがextensionというキーを持っているので、これを対象にしてaggregationを実行してみた。

curl -X POST -H "Content-Type:application/json" "localhost:9200/logstash-*/_search" -d '
{
  "aggs": {
    "by_extension": {
      "terms": {
        "field": "extension.keyword"
      }
    }
  }
}'

これを実行すると以下のような結果が返ってくる。

{
  "took": 26,
  ...
  },
  "hits": {
    "total": 14005,
    ...
  },
  "aggregations": {
    "by_extension": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "jpg",
          "doc_count": 9165
        },
        {
          "key": "css",
          "doc_count": 2253
        },
        {
          "key": "png",
          "doc_count": 1303
        },
        {
          "key": "gif",
          "doc_count": 887
        },
        {
          "key": "php",
          "doc_count": 397
        }
      ]
    }
  }
}

この場合、extensionキーの値ごとにドキュメント数がカウントされている。
今回実行したものは、SQLで言うところのSELECT extension, count(*) FROM logstash-* GROUP BY extension;に相当する。

aggregation機能には、日付を元に一定間隔で含まれるドキュメントを集計したり、計算方法もカウント以外に数値データの合計や平均、最大を求めることもできる。
また、複数の集計条件を指定することも可能。
queryやfilterと組み合わせて「特定の条件で検索した結果に対して集計を実行する」ということもできる。

注意点としては、stringタイプのものを集計の基準に選ぶ場合は「xxx.keyword」を指定する必要がある。
集計が必要なインデックスについては、集計のキーをどれにするか、どのようなタイプで登録するかを予め考慮して設定しておいたほうが良い。

基本的な文法は上記のようになるが、詳細は公式サイトを参照が詳しい。

Reference

2
6
0

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
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?