LoginSignup
0
0

More than 3 years have passed since last update.

Elasticsearchの検索クエリについて

Posted at

概要

Elasticsearchで色々とデータを検索するために調べたことのまとめ。

クエリの実行

curl等を使ったHTTPリクエストの場合は以下のような形式でクエリを投げます。
curl -XGET 'localhost:9200/**_index/_search?pretty' -d '{JSON_QUERY}'

基本的な検索QUERY

  • SELECT *
{
    "query": { "match_all": {} }
}
  • SELECT a, b, c
{
    "query": { "match_all": {} },
    "_source": ["a", "b", "c"]
}
  • WHERE
{
    "query": {
        "match": { "a": 20 }
    }
}
  • WHERE AND
{
    "query": {
        "bool": {
            "must": [
                { "match": { "a": 20 } },
                { "match": { "b": "hoge" } }
            ]
        }
    }
}
  • GROUP BY
{
    "aggs": {
        "hogehoge": {
            "terms": {
                "field": "a"
            }
        }
    }
}
  • idごとに最新のレコードを取りたい
{
    "aggs": {
        "hogehoge": {
            "terms": {
                "field": "id"
            },
            "aggs": {
                "hoge_top_hits": {
                    "top_hits": {
                        "sort": [
                            {
                                "timestamp": {
                                    "order": "desc"
                                }
                            }
                        ],
                        "_source": {
                            "includes": [ "a", "b" ]
                        },
                        "size": 1
                    }
                }
            }
        }
    }
}

termsでidごとのAggregationBucketを作成し、それぞれのBucketでtimestamp順に並び替えてa,bのデータを1つだけとってます。

  • idごとに最新のレコードを取り、それに対してフィルターをかける
    • Aggsに対してフィルターをかける方法はいくつかある
      • filter
      • bucket_selector
0
0
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
0
0