LoginSignup
6
1

More than 1 year has passed since last update.

Elasticsearchのもやもや: 文字列のデータ型はtextかkeywordか

Last updated at Posted at 2022-08-25

はじめに

Elasticsearchを使っていて、もやもやした内容を、
メモ書きレベルで、思うがまま書いてみます。

Elasticsearchでtext型とkeyword型のフィールド

Elasticsearchで、文章など文字列を格納/検索する場合、
フィールドデータ型として、textまたはkeywordを使用できます。
その違いや使い分けに、モヤモヤ感が。。。

text型とkeyword型を比較してみた

  • Analyzer(解析)を使って文字列を単語分割するか

    • text: 必要、検索で転置インデックスを使用するため
    • keyword: 不要、文字列全体を一つとして扱う
  • 検索方法

    • text: 文字列を分割された単語で全文検索
    • keyword: 文字列を完全一致で検索
  • 使用例

    • text: { "description": "これはPythonプログラミングの本です。" }
      • これ/Python/プログラミング/のように単語分割し検索
    • keyword: { "email": "test@test.com" }
      • test@test.comのように完全一致で検索

同じフィールドを、text型としてもkeyword型としても使用したい

  • マルチフィールド型(multi-fields)を使用

※ 引用元: https://www.elastic.co/guide/en/elasticsearch/reference/current/multi-fields.html

  • マルチフィールド型のマッピング定義
PUT index
{
  "mappings": {
    "properties": {
      "city": {
        "type": "text",
        "fields": {
          "raw": { 
            "type":  "keyword"
          }
        }
      }
    }
  }
}
  • cityは、keyword型とtext型二つの機能を兼ね備える
    • city.rawフィールドでkeyword型を表し、ソートやaggregrationに使用
    • cityフィールドでtext型を表し、単語単位の全文検索に使用

おわりに

Elasticsearchの文字列を扱うデータ型として、
textとkeywordの違いを理解しました。

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