検索のやりかたいろいろ - accgetter/Elasticsearch GitHub Wiki

index に縛られず全件取得する検索

Multiple Indices

http://localhost:9200/_all/_search

複数フィールドのAND検索(完全一致)

事前にMappingが必要 bool, must を使う。 例) referer='Yahoo' and url='Google' のドキュメントがヒットする。

{
  "query": {
    "bool": {
            "must": [
              {
                "match": {
                  "referer": "Yahoo"
                }
              },
              {
                "match": {
                  "url": "Google"
                }
              }
            ]
    }
  }
}

取得件数の指定

From / Size

http://localhost:9200/_all/_search?size=1000

または、以下のparameterを付与

{
"from" : 0, "size" : 1000
}

Aggregationsでユニーク数を取得する

Cardinality Aggregation

      "aggs" : {
        "distinct_uid" : {
            "cardinality" : {
              "field" : "uid"
            }
        }
    }

Script を使う場合

elasticsearch.yml に以下の記述を追記する必要がある。

script.engine.groovy.inline.aggs: on

https://discuss.elastic.co/t/scripts-of-type-inline-operation-aggs-and-lang-groovy-are-disabled/2493

Aggregationを複数実行する例

terms(aggrigation type)と同じ階層になって、 Aggregationの定義が入れ子になる。

GET /_all/access/_search?pretty=true
{
  "aggs" : {
    "route" : {
      "terms" : {
        "script" : "doc['referer'].value + ' ' + doc['url'].value",
          "size" : 1000
      },
        "aggs" : {
          "distinct_uid" : {
            "cardinality" : {
              "field" : "uid"
            }
          }
        }
    }
  }
}

複数fieldのterms

Multi-field terms aggregation script の設定が必要

GET /_all/access/_search?pretty=true
{
  "aggs" : {
    "route" : {
      "terms" : {
        "script" : "doc['referer'].value + ' ' + doc['url'].value",
          "size" : 1000
      }
    }
  }
}