當 Elasticsearch 遇到文檔中以前未遇到的字段,它用 dynamic mapping(動態映射) 來確定字段的數據類型並自動把新的字段添加到類型映射。有時這是想要的行為,有時又不希望這樣。通常沒有人知道以後會有什麼新字段加到文檔,但是又希望這些字段被自動的索引。如果Elasticsearch是作為重要的數據存儲,可能就會期望遇到新字段就會拋出異常,這樣能及時發現問題。
一、dynamic設置
true:默認值,遇到陌生字段就動態映射(dynamic mapping);
false:遇到陌生字段就忽略;
strict:遇到陌生字段就拋出異常;
二、創建users索引
PUT users
{
"settings":{
"number_of_shards": 3,
"number_of_replicas": 0
},
"mappings":{
"dynamic": "strict",
"properties": {
"name": {"type": "text"},
"address": {"type": "object", "dynamic": true}
}
}
}
三、插入文檔
插入以下文檔,將會報錯。users設置dynamic是strict,請求報文中添加age節點將報錯,在address層設置dynamic是ture,將動態映射生成字段。
PUT users/_doc/1
{
"name": "rickie",
"age": "20",
"address": {
"province": "shanghai",
"city": "上海"
}
}
錯誤信息如下:
{
"error": {
"root_cause": [
{
"type": "strict_dynamic_mapping_exception",
"reason": "mapping set to strict, dynamic introduction of [age] within [_doc] is not allowed"
}
],
"type": "strict_dynamic_mapping_exception",
"reason": "mapping set to strict, dynamic introduction of [age] within [_doc] is not allowed"
},
"status": 400
}
PUT users/_doc/1
{
"name": "rickie",
"address": {
"province": "shanghai",
"city": "上海"
}
}
這次可以成功插入文檔記錄:
{
"_index" : "users",
"_type" : "_doc",
"_id" : "1",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 1,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1
}
閱讀更多 軟件架構 的文章
關鍵字: ElasticSearch 上海 映射