ES修改index下某字段类型

317 阅读1分钟

ES修改index下某字段类型

ES不能直接修改某字段的索引类型,因此需要一些别的方法。

在数据量不大的情况下,可以通过官方的reindex方法完成迁移。具体原理为:

通过建立新索引、迁移数据、为新索引建立别名为旧索引的方法完成一种访问上的迁移。

1、新建一个index,并定义mapping,mapping结构与原索引一致,type改为需要改的类型

curl -X PUT "http://ip:port/new_index_name" -H 'Content-Type: application/json' -d'
{
  "mappings": {
            "properties": {
                "_class": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "createTime": {
                    "type": "date"
                },
                "xxxx": {
                    "type": "keyword"
                }
            }
        }
}'

2、设置原index为只读

目的是,防止迁移过程中产生新数据,导致数据不一致

curl -X PUT "http://ip:port/old_index_name/_settings" -H 'Content-Type: application/json' -d'
{
  "settings": {
    "index.blocks.write": true
  }
}'

3、迁移数据

curl -X POST "http://ip:port/_reindex" -H 'Content-Type: application/json' -d'
{
  "source": {
    "index": "old_index_name"
  },
  "dest": {
    "index": "new_index_name"
  }
}'

4、恢复可读写

curl -X PUT "http://ip:port/old_index_name/_settings" -H 'Content-Type: application/json' -d'
{
  "settings": {
    "index.blocks.write": false
  }
}'

5、在这里查看一下新索引的数据,观察是否成功迁移

curl -X GET "http://ip:port/new_index_name/_search" -H 'Content-Type: application/json' -d '
{
    "query": {
      "match_all": {}
    }
}'

6、如果数据相同,删除原索引

curl -X DELETE "http://ip:port/old_index_name"

7、为新建立的索引命别名

curl -X PUT "http://ip:port/new_index_name/_alias/old_index_name"

8、查看新索引是否有原本索引的别名

curl -X GET "http://ip:port/new_index_name/_alias"

修改字段类型方法到此结束

当数据量小时,并且希望mapping比较规整好看,该方案是比较推荐的。当数据量大时,不建议使用此方法。

本文参考 www.zhihu.com/question/55…