ElasticSearch 动态映射与静态映射_08
映射就是 Mapping,它用來定義一個文檔以及文檔所包含的字段該如何被存儲和索引。所以,它其實(shí)有點(diǎn)類似于關(guān)系型數(shù)據(jù)庫中表的定義。
映射分類
動態(tài)映射
顧名思義,就是自動創(chuàng)建出來的映射。es 根據(jù)存入的文檔,自動分析出來文檔中字段的類型以及存儲方式,這種就是動態(tài)映射。
舉一個簡單例子,新建一個索引,然后查看索引信息:
在這里插入代碼片在創(chuàng)建好的索引信息中,可以看到,mappings 為空,這個 mappings 中保存的就是映射信息。
現(xiàn)在我們向索引中添加一個文檔,如下:
PUT blog/_doc/1 {"title":"1111","date":"2020-11-11" }文檔添加成功后,就會自動生成 Mappings:
可以看到,date 字段的類型為 date,title 的類型有兩個,text 和 keyword。
默認(rèn)情況下,文檔中如果新增了字段,mappings 中也會自動新增進(jìn)來。
有的時候,如果希望新增字段時,能夠拋出異常來提醒開發(fā)者,這個可以通過 mappings 中 dynamic 屬性來配置。
dynamic 屬性有三種取值:
true,默認(rèn)即此。自動添加新字段。
false,忽略新字段。
strict,嚴(yán)格模式,發(fā)現(xiàn)新字段會拋出異常。
具體配置方式如下,創(chuàng)建索引時指定 mappings(這其實(shí)就是靜態(tài)映射):
然后向 blog 中索引中添加數(shù)據(jù):
PUT blog/_doc/2 {"title":"1111","date":"2020-11-11","age":99 }在添加的文檔中,多出了一個 date 字段,而該字段沒有預(yù)定義,所以這個添加操作就會報(bào)錯:
{"error" : {"root_cause" : [{"type" : "strict_dynamic_mapping_exception","reason" : "mapping set to strict, dynamic introduction of [date] within [_doc] is not allowed"}],"type" : "strict_dynamic_mapping_exception","reason" : "mapping set to strict, dynamic introduction of [date] within [_doc] is not allowed"},"status" : 400 }動態(tài)映射還有一個日期檢測的問題。
例如新建一個索引,然后添加一個含有日期的文檔,如下:
PUT blog/_doc/1 {"remark":"2020-11-11" }添加成功后,remark 字段會被推斷是一個日期類型。
此時,remark 字段就無法存儲其他類型了。
此時報(bào)錯如下:
{"error" : {"root_cause" : [{"type" : "mapper_parsing_exception","reason" : "failed to parse field [remark] of type [date] in document with id '1'. Preview of field's value: 'javaboy'"}],"type" : "mapper_parsing_exception","reason" : "failed to parse field [remark] of type [date] in document with id '1'. Preview of field's value: 'javaboy'","caused_by" : {"type" : "illegal_argument_exception","reason" : "failed to parse date field [javaboy] with format [strict_date_optional_time||epoch_millis]","caused_by" : {"type" : "date_time_parse_exception","reason" : "Failed to parse with all enclosed parsers"}}},"status" : 400 }要解決這個問題,可以使用靜態(tài)映射,即在索引定義時,將 remark 指定為 text 類型。也可以關(guān)閉日期檢測。
PUT blog {"mappings": {"date_detection": false} }此時日期類型就回當(dāng)成文本來處理。
類型推斷
es 中動態(tài)映射類型推斷方式如下:
| null | 沒有字段被添加 |
| true/false | boolean |
| 浮點(diǎn)類型 | float |
| 數(shù)字 | long |
| json對象 | object |
| string | text/keyword/date/double/long |
總結(jié)
以上是生活随笔為你收集整理的ElasticSearch 动态映射与静态映射_08的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpingBoot 整合 kafka E
- 下一篇: CentOS 7.8使用devtools