侧边栏壁纸
博主头像
慧棱镜 All In One 服务平台 博主等级

行动起来,活在当下

  • 累计撰写 35 篇文章
  • 累计创建 63 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

ElasticSearch如何实现创建完索引后不能再自动新增字段?

创始者
2025-01-11 / 0 评论 / 0 点赞 / 4 阅读 / 0 字
广告 广告

在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

}

通过这种方式,可以有效地防止后续新增字段。

0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin
广告 广告

评论区