ES 12 - 如何配置使用Elasticsearch的動態映射 (dynamic mapping)


寫在前面: 本文涉及到的演示以ES 6.6.0版本, 其他版本可能存在不同, 還請讀者朋友們注意.

1 動態映射(dynamic mapping)

1.1 什么是動態映射

動態映射時Elasticsearch的一個重要特性: 不需要提前創建iindex、定義mapping信息和type類型, 你可以 直接向ES中插入文檔數據時, ES會根據每個新field可能的數據類型, 自動為其配置type等mapping信息, 這個過程就是動態映射(dynamic mapping).

Elasticsearch動態映射的示例:

字段內容(field) 映射的字段類型(type)
true | false boolean
1234 long
123.4 float
2018-10-10 date
"hello world" text

說明: 動態映射雖然方便, 可並不直觀, 為了個性化自定義相關設置, 可以在添加文檔之前, 先創建index和type, 並配置type對應的mapping, 以取代動態映射.
mapping的配置可參考博文: ES 11 - 如何配置Elasticsearch的映射 (mapping).

1.2 體驗動態映射

(1) 插入如下數據:

如果已有website索引, 先刪除DELETE blog , 再執行下面的插入操作: .

PUT blog/_doc/1
{
    "blog_id": 10001,
    "author_id": 5520,
    "post_date": "2018-01-01",
	  "title": "my first blog",
	  "content": "my first blog in the website"
}

PUT blog/_doc/2
{
    "blog_id": 10002,
    "author_id": 5520,
    "post_date": "2018-01-02",
    "title": "my second blog",
    "content": "my second blog in the website"
}

PUT blog/_doc/3
{
    "blog_id": 10003,
    "author_id": 5520,
    "post_date": "2018-01-03",
    "title": "my third blog",
    "content": "my third blog in the website"
}

(2) 進行如下檢索測試:

注意這里結果數是3的情況.

GET blog/_search?q=2018                 // 1條結果, 5.6之前的版本是3條結果
GET blog/_search?q=2018-01-01           // 1條結果, 5.6之前的版本是3條結果
GET blog/_search?q=post_date:2018       // 1條結果
GET blog/_search?q=post_date:2018-01-01	// 1條結果

(3) 查看ES自動建立的mapping:

GET blog/_mapping

// 結果如下:
{
  "blog" : {                  // index是blog
    "mappings" : {
      "_doc" : {              // type是_doc - 方便后期升級版本
        "properties" : {
          "author_id" : {
            "type" : "long"
          },
          "blog_id" : {
            "type" : "long"
          },
          "content" : {
            "type" : "text",
            "fields" : {
              "keyword" : {
                "type" : "keyword",
                "ignore_above" : 256
              }
            }
          },
          "post_date" : {
            "type" : "date"  // 日期"2018-01-01"被自動識別為date類型
          },
          "title" : {
            "type" : "text",
            "fields" : {
              "keyword" : {
                "type" : "keyword",
                "ignore_above" : 256
              }
            }
          }
        }
      }
    }
  }
}

1.3 搜索結果不一致的原因分析

如果使用的是ES 5.6.x之前的版本, [1.2]節中搜索結果會不一致, 這是因為:

ES自動建立mapping時, 為不同的field映射了不同的數據類型, 而不同數據類型在分詞、搜索等行為上也是不同的.

我們通過q=xxx的方式搜索, 底層是從每個文檔的_all字段中進行匹配的 —— ES默認將每個文檔的所有field的值抽取到一個名為_all的元字段中.

官方文檔指出, 從6.0+版本開始, _all字段就被禁止使用了, 建議我們使用copy_to實現相似的功能.—— 也就是說, 如果_all字段被關閉, 就不會出現搜索結果不一致的情況.

(1) GET website/blog/_search?q=2018

id=1的文檔的_all的值為:

2018-01-01 my first blog my first blog in the website 5520

說明: _all字段將所有的值作為字符串索引, 所以日期被索引為年、月、日三個值, _all字段的倒排索引結果如下:

doc1 doc2 Doc3
2018 * * *
01 * * *
02 *
03 *

此項搜索中, ES是從_all字段中檢索, 3個文檔中都有 2018 , 所以結果數是3.

(2) GET website/blog/?q=2018-01-01

同(1), ES也是從_all字段中檢索, 結果數同樣是3.

(3) GET website/blog/_search?q=post_date:2018-01-01

此檢索指定了檢索條件, ES將從post_date字段中檢索, 而post_date被映射為date類型, 所以將進行精確匹配.

而date類型的字段索引的內容有其默認的固定格式. post_date字段的倒排索引結果如下:

doc1 doc2 doc3
2018-01-01 00:00:00 UTC *
2018-01-02 00:00:00 UTC *
2018-01-03 00:00:00 UTC *

可以看出, 滿足條件的只有1個結果, 即doc1.

(4) GET /_search?q=post_date:2018

這是ES 5.x版本中做的一個優化, 搜索post_date:01等是不會出現結果的, 搜索2018會出現第一條結果.

2 開啟dynamic mapping動態映射策略

2.1 約束策略

策略 功能說明
true 開啟 —— 遇到陌生字段時, 進行動態映射
false 關閉 —— 忽略遇到的陌生字段
strict 遇到陌生字段時, 作報錯處理

2.2 策略示例

(1) 使用不同的約束策略:

PUT blog_user
{
  "mappings": {
      "_doc": {
          "dynamic": "strict",			// 嚴格控制策略
          "properties": {
              "name": { "type": "text" },
              "address": {
                  "type": "object",
                  "dynamic": "true"		// 開啟動態映射策略
              }
          }
      }
  }
}

(2) 插入數據演示:

// 插入數據時多添加一個字段
PUT blog_user/1
{
    "name": "shou feng",
    "content": "this is my blog",  // 多添加的字段
    "address": {
        "province": "guangdong",
        "city": "guangzhou"
    }
}

將拋出如下錯誤信息:

{
  "error": {
    "root_cause": [
      {
        "type": "strict_dynamic_mapping_exception",
        // 錯誤原因: 不允許動態添加field
        "reason": "mapping set to strict, dynamic introduction of [content] within [_doc] is not allowed"
      }
    ],
    "type": "strict_dynamic_mapping_exception",
    "reason": "mapping set to strict, dynamic introduction of [content] within [_doc] is not allowed"
  },
  "status": 400
}

添加符合約束的數據, 操作就能成功:

PUT blog_user/_doc/1
{
    "name": "shou feng",
    "address": {
        "province": "guangdong",
        "city": "guangzhou"
    }
}

(3) 查看映射信息:

GET user/_mapping

// 映射信息如下: 
{
  "blog_user" : {
    "mappings" : {
      "_doc" : {
        "dynamic" : "strict",      // 嚴格約束條件
        "properties" : {
          "address" : {
            "dynamic" : "true",    // 開啟動態映射策略
            "properties" : {
              "city" : {
                "type" : "text",
                "fields" : {
                  "keyword" : {
                    "type" : "keyword",
                    "ignore_above" : 256
                  }
                }
              },
              "province" : {
                "type" : "text",
                "fields" : {
                  "keyword" : {
                    "type" : "keyword",
                    "ignore_above" : 256
                  }
                }
              }
            }
          },
          "name" : {
            "type" : "text"
          }
        }
      }
    }
  }
}

3 定制dynamic mapping策略

3.1 date_detection - 日期識別策略

對於date類型的數據, Elasticsearch有其默認的識別策略, 比如"yyyy-MM-dd". 存在這種情況:

① 第一次添加文檔時, 某個field是類似"2018-01-01"的值, 其類型就動態映射成date;
② 后期再次添加文檔, 該field是類似"hello world"的值, ES就會因為類型不匹配而報錯.

為解決這一問題, 可以手動關閉某個type的date_detection; 如果不需要關閉, 建議手動指定這個field為date類型. 示例如下:

PUT blog_user/_mapping/_doc
{
    "date_detection": false
}

3.2 在type中自定義動態映射模板

(1) 在type中定義動態映射模板(dynamic mapping template) —— 把所有的String類型映射成text和keyword類型:

先刪除已有的blog_user索引: DELETE blog_user, 再執行下述命令:

PUT blog_user
{
    "mappings": {
        "_doc": {
            "dynamic_templates": [
                {
                    "en": {       // 動態模板的名稱
                        "match": "*_en",           // 匹配名為"*_en"的field
                        "match_mapping_type": "string",
                        "mapping": {
                            "type": "text",        // 把所有的string類型, 映射成text類型
                            "analyzer": "english", // 使用english分詞器
                            "fields": {
                                "raw": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
}

(2) 添加數據:

PUT blog_user/_doc/1
{
    "name": "the first register user"
}

PUT blog_user/_doc/2
{
    "name_en": "the second register user"
}

(3) 檢索數據:

// 有結果: "name"沒有匹配到任何動態模板, 默認使用standard分詞器
GET blog_user/_search
{
    "query": {
        "match": {"name": "the"}
    }
}

// 無結果: "name_en"匹配到了動態模板, 使用english分詞器, the是停用詞, 被過濾掉了
GET blog_user/_search
{
    "query": {
        "match": {"name_en": "the"}	
    }
}

說明:

這里的match_mapping_type的類型支持 [object, string, long, double, boolean, date, binary], 若使用text將拋出如下錯誤信息:

{
  "error": {
    "root_cause": [
      {
        "type": "mapper_parsing_exception",
        "reason": "Failed to parse mapping [_doc]: No field type matched on [text], possible values are [object, string, long, double, boolean, date, binary]"
      }
    ],
    "type": "mapper_parsing_exception",
    "reason": "Failed to parse mapping [_doc]: No field type matched on [text], possible values are [object, string, long, double, boolean, date, binary]",
    "caused_by": {
      "type": "illegal_argument_exception",
      "reason": "No field type matched on [text], possible values are [object, string, long, double, boolean, date, binary]"
    }
  },
  "status": 400
}

在6.0之前的版本, 將拋出如下過期的警告信息:

Deprecation: match_mapping_type [text] is invalid and will be ignored: 
No field type matched on [text], possible values are [object, string, long, double, boolean, date, binary]

3.3 [過期]在index中自定義默認映射模板

_default mapping - 默認映射模板是類似於全局變量的存在, 對當前配置的索引起作用.

默認映射模板在Elasticsearch 6.x版本中已經不再支持, 因為6.0版本開始, 每個索引只能有一個類型, 因此默認模板沒有存在的意義了.

下面的演示過程, 是在6.0之前的版本上的測試.

(1) 在index中定義默認映射模板(default mapping template):

先刪除已有的blog_user索引: DELETE blog_user, 再執行下述命令:

PUT blog_user
{
    "mappings": {
        "_default_": {
            "_all": { "enabled":  false }
        },
        "_doc": {
            "_all": { "enabled":  true  }
        }
    }
}

(2) 動態映射可以和索引模板(Index Templates)配合使用.

無論是自動創建Index, 還是手動顯式創建Index, 索引模板都可以用來配置新索引的默認mappings(映射)、settings(配置項)和aliases(別名). 具體使用方法請參考博客: ES 10 - 如何使用Elasticsearch的索引模板(index template)


參考資料

(6.6版)官方文檔 - Dynamic Mapping

版權聲明

作者: 瘦風(https://healchow.com)

出處: 博客園 瘦風(https://www.cnblogs.com/shoufeng)

感謝閱讀, 如果文章有幫助或啟發到你, 點個[好文要頂👆] 或 [推薦👍] 吧😜

本文版權歸博主所有, 歡迎轉載, 但 [必須在文章頁面明顯位置標明原文鏈接], 否則博主保留追究相關人員法律責任的權利.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM