65_索引管理_定製化自己的dynamic mapping策略

5765809發表於2024-10-02

課程大綱

1、定製dynamic策略

true:遇到陌生欄位,就進行dynamic mapping
false:遇到陌生欄位,就忽略
strict:遇到陌生欄位,就報錯

PUT /my_index
{
"mappings": {
"my_type": {
"dynamic": "strict",
"properties": {
"title": {
"type": "text"
},
"address": {
"type": "object",
"dynamic": "true"
}
}
}
}
}

PUT /my_index/my_type/1
{
"title": "my article",
"content": "this is my article",
"address": {
"province": "guangdong",
"city": "guangzhou"
}
}

{
"error": {
"root_cause": [
{
"type": "strict_dynamic_mapping_exception",
"reason": "mapping set to strict, dynamic introduction of [content] within [my_type] is not allowed"
}
],
"type": "strict_dynamic_mapping_exception",
"reason": "mapping set to strict, dynamic introduction of [content] within [my_type] is not allowed"
},
"status": 400
}

PUT /my_index/my_type/1
{
"title": "my article",
"address": {
"province": "guangdong",
"city": "guangzhou"
}
}

GET /my_index/_mapping/my_type

{
"my_index": {
"mappings": {
"my_type": {
"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
}
}
}
}
},
"title": {
"type": "text"
}
}
}
}
}
}

2、定製dynamic mapping策略

(1)date_detection

預設會按照一定格式識別date,比如yyyy-MM-dd。但是如果某個field先過來一個2017-01-01的值,就會被自動dynamic mapping成date,後面如果再來一個"hello world"之類的值,就會報錯。可以手動關閉某個type的date_detection,如果有需要,自己手動指定某個field為date型別。

PUT /my_index/_mapping/my_type
{
"date_detection": false
}

(2)定製自己的dynamic mapping template(type level)

PUT /my_index
{
"mappings": {
"my_type": {
"dynamic_templates": [
{ "en": {
"match": "*_en",
"match_mapping_type": "string",
"mapping": {
"type": "string",
"analyzer": "english"
}
}}
]
}}}

PUT /my_index/my_type/1
{
"title": "this is my first article"
}

PUT /my_index/my_type/2
{
"title_en": "this is my first article"
}

title沒有匹配到任何的dynamic模板,預設就是standard分詞器,不會過濾停用詞,is會進入倒排索引,用is來搜尋是可以搜尋到的
title_en匹配到了dynamic模板,就是english分詞器,會過濾停用詞,is這種停用詞就會被過濾掉,用is來搜尋就搜尋不到了

(3)定製自己的default mapping template(index level)

PUT /my_index
{
"mappings": {
"default": {
"_all": { "enabled": false }
},
"blog": {
"_all": { "enabled": true }
}
}
}

相關文章