在Elasticsearch中,可以通过设置`dynamic`参数来控制索引是否允许新增字段。具体操作如下:
1. 创建索引时设置`dynamic`参数
在创建索引时,可以将`dynamic`参数设置为`strict`,这样当尝试添加未定义的字段时,Elasticsearch会报错,从而禁止新增字段。
PUT my_index
{
"mappings": {
"dynamic": "strict",
"properties": {
"title": {
"type": "text"
},
"name": {
"type": "keyword"
},
"age": {
"type": "integer"
}
}
}
}
2. 已创建索引后修改`dynamic`参数
如果索引已经创建,但需要禁止后续新增字段,可以通过更新索引的映射(mapping)来实现。将`dynamic`参数设置为`strict`:
PUT my_index/_mapping
{
"dynamic": "strict"
}
这样,后续尝试添加未定义的字段时,Elasticsearch会报错,从而禁止新增字段。
3. dynamic
参数的其他值
- true
:默认值,允许自动新增字段。
- false
:不允许自动新增字段,但不会报错,只会忽略新增的字段。
### 示例
假设你有一个已创建的索引`my_index`,并且希望禁止后续新增字段:
1. 创建索引(如果尚未创建):
PUT my_index
{
"mappings": {
"properties": {
"title": {
"type": "text"
},
"name": {
"type": "keyword"
},
"age": {
"type": "integer"
}
}
}
}
2. 修改索引映射:
PUT my_index/_mapping
{
"dynamic": "strict"
}
之后,尝试插入包含未定义字段的文档时,Elasticsearch会报错:
PUT my_index/_doc/1
{
"title": "Hello World",
"desc": "This is a test"
}
这将导致以下错误:
{
"error": {
"root_cause": [
{
"type": "illegal_argument_exception",
"reason": "Mapper for [desc] conflicts with existing mapping in other types:"
}
],
"type": "illegal_argument_exception",
"reason": "Mapper for [desc] conflicts with existing mapping in other types:"
},
"status": 400
}
通过这种方式,可以有效地防止后续新增字段。
评论区