前言

我们都知道,在ES中一旦声明了字段名称,就不能对字段名称进行修改了。只能新增字段,不能删除、修改已经声明的mapping字段。
那么,如果我们需要修改mapping中的字段名称,需要怎么操作呢?


一、分析

不能直接修改原索引中的mapping字段,那么只能在新索引中重命名索引字段,然后将数据导入到新索引。
而ES中重建索引命令_reindex正好能很好的支持这一点。

官网说明:docs-reindex-change-name

二、实战

1、创建索引test并插入数据

POST test/_doc/1?refresh
{
  "text": "words words",
  "flag": "foo"
}

2、通过reindex重命名字段名称

说明:
将原索引test中的字段flag重命名为tag

POST _reindex
{
  "source": {
    "index": "test"
  },
  "dest": {
    "index": "test2"
  },
  "script": {
    "source": "ctx._source.tag = ctx._source.remove(\"flag\")"
  }
}

3、查看结果

##根据id查看记录
GET test2/_doc/1
## 返回结果
{
  "found": true,
  "_id": "1",
  "_index": "test2",
  "_type": "_doc",
  "_version": 1,
  "_seq_no": 44,
  "_primary_term": 1,
  "_source": {
    "text": "words words",
    "tag": "foo"
  }
}

总结

本文主要介绍如何通过索引重建reindex+script脚本实现修改索引字段名称。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐