当 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
}
閱讀更多 軟件架構 的文章