LoginSignup
14
10

More than 5 years have passed since last update.

Elasticsearchで、正規表現での検索結果が思い通りにならなかったことへの対応

Last updated at Posted at 2016-07-13

Elasticsearch、とても良いですね。
実際に使ってみて、思いついた条件でログをすぐに分析できる素晴らしさを知りました。

以下本題。

前提環境

  • Elasticsearch 2.3.4
  • Kibana 4.5.2
  • Fluentd 2.3.1
  • nginx

nginxのLTSVなログをFluentdでElasticsearchに流し込み、
Kibanaで見るという、よくありそうな構成です。

UAが思い通りに検索できない!

Kibana上で、特定のUAを持ったログを検索したいとおもい、下記のようなクエリを投げました。

  • 検索したいログの例
見つけたいログ(少し改変しています)
ua:PlayStation Vita Dummy Dummy (PS Vita)
  • 検索クエリ
クエリ(NG)
 ua:/.*Vita.*/

しかし検索結果が出ない!おかしい!
そこで、下記のように少しクエリを変えました。

クエリ(OK)
 ua:/.*ita.*/

これだと検索結果に正常に出てきます。
正規表現的には、どちらでも見つかるはずですが・・・。

Elasticsearchの設定

下記のようなindex templateを登録しています。

index_template
{
  "order": 0,
  "template": "*",
  "settings": {},
  "mappings": {
    "_default_": {
      "_source": {
        "enabled": true
      },
      "dynamic_templates": [
        {
          "string_template": {
            "mapping": {
              "index": "not_analyzed",
              "type": "string"
            },
            "match_mapping_type": "string",
            "match": "*"
          }
        }
      ],
      "properties": {
        "@timestamp": {
          "index": "not_analyzed",
          "type": "date"
        }
      }
    }
  },
  "aliases": {}
}

文字列の検索時にうまいこと検索できると思い、indexにはnot_analyzedを指定していました。

変更後

調べてみると、検索時のanalyzerが影響をしていそうでした。
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-analyzer.html

そこで、今回は、下記のようなsettingをテンプレートに追加し、

index_template(settings)
{
  "order": 0,
  "template": "*",
  "settings": {
    "index": {
      "analysis": {
        "analyzer": {
          "tabAnalyzer": {
            "type": "pattern",
            "pattern": "\t"
          }
        }
      }
    }
  }

mappingsのテンプレートを下記のように変更しました

  • not_analyzedをanalyzedに変更
  • analyzerを、settingsで定義した「tabAnalyzer」に変更
index_template(mappings)
{
  "order": 0,
  "template": "*",
  "settings": {},
  "mappings": {
    "_default_": {
      "_source": {
        "enabled": true
      },
      "dynamic_templates": [
        {
          "string_template": {
            "mapping": {
              "index": "analyzed",
              "analyzer": "tabAnalyzer", 
              "type": "string"
            },
            "match_mapping_type": "string",
            "match": "*"
          }
        }
      ],
      "properties": {
        "@timestamp": {
          "index": "not_analyzed",
          "type": "date"
        }
      }
    }
  }
}

変更後の検索結果

先ほどと同じ、下記クエリを投げると・・・

クエリ
 ua:/.*Vita.*/

今度は予想通りの検索結果が帰ってきました!

その他

検索時に、analyzerを指定出来るのですが、それでも解決できた問題なのかもしれません(未調査)。

14
10
2

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
14
10