使用Reindex迁移Elasticsearch集群数据详解(上)
#作者:stackofumbrella
文章目录
- Reindex简介
- 应用场景
- Reindex基本使用
- 命令行
- 将多个索引reindex到一个目标
- 使用脚本
- 使用Ingest Node
Reindex简介
Reindex是Elasticsearch中一种将数据从一个索引复制到另一个索引的操作,主要用途包括:
- 索引结构变更:当需要修改映射设置,但无法直接更新现有索引时。
- 数据迁移:将数据从一个索引或集群迁移到另一个索引或集群。
- 数据转换:在迁移过程中对数据进行修改或过滤。
- 分片优化:调整分片数量或分片策略。
- 版本升级:跨大版本升级时重建索引。
Reindex本质上是Elasticsearch内部的一个数据复制过程,它不是简单的文件复制,而是重新索引文档的过程。从源索引读取文档,可选地对文档进行转换,将文档写入目标索引。
应用场景
当数据量过大,而索引最初创建的分片不足,导致数据入库较慢, 此时需要扩大分片数量,可以使用Reindex。
当数据的mapping需要修改,但大量的数据已经导入到索引中,重新导入数据到新的索引太耗时,同时ES的mapping一旦定义之后是不允许修改的,这时可以用Reindex。
注意事项
源和目的不能相同, 比如不能将数据流Reindex给它自身。源索引的文档中_source字段必须开启。Reindex不会复制源的setting和源所匹配的模板, 因此在调用_reindex前, 需要设置好目的索引 (action.auto_create_index 为 false或者-.*时)。目标索引的mapping,主分片数,副本数等推荐提前配置。
如果Elasticsearch集群配置了安全策略和权限策略, 则进行Reindex必须拥有以下权限:
读取源的数据流、索引、索引别名等索引级别权限。
对于目的数据流、索引、索引别名的写权限。
如果需要使用Reindex API自动创建数据流和索引, 则必须拥有对目的数据流、索引、索引别名的auto_configure、 create_index或manage等索引级别权限。
如果源为远程的集群,则source.remote.user用户必须拥有集群监控权限和读取源索引、源索引别名、源数据流的权限。
如果Reindex的源为远程集群, 必须在当前集群的请求节点elasticsearch.yml文件配置远程白名单reindex.remote.whitelist。
创建数据流需要提前配置好数据流的匹配索引模板,参考文档:https://www.elastic.co/guide/en/elasticsearch/reference/7.11/set-up-a-data-stream.html
Reindex基本使用
迁移旧索引到新索引
POST _reindex
{"source": {"index": "old_index"},"dest": {"index": "new_index"}
}
命令行
$ curl -XPOST 'http://127.0.0.1:9200/_reindex' -d{"source":{"index:"old_index""}, "dest":{"index":"new_index"}}
将多个索引reindex到一个目标
POST _reindex
{"source": {"index": ["weixin", "blog"],"type": ["tweet", "post"]},"dest": {"index": "all_family"}
}
这里需要注意的是如果weixin和blog中有document的id是一样的,就无法保证最终出现在all_family里面的document是哪个,因为迭代是随机的,最后一个会覆盖前一个。
只复制特定的field
POST _reindex
{"source": {"index": "mm","_source": ["user", "tweet"]},"dest": {"index": "new_mm"}
}
使用脚本
POST _reindex
{"source": {"index": "mm"},"dest": {"index": "new_mm","version_type": "external"},"script": {"source": "if (ctx._source.foo == 'bar') {ctx._version++; ctx._source.remove('foo')}","lang": "painless"}
}
使用Ingest Node
这个功能是最好用的,当source是因为不合理的结构,需要重新结构化所有的数据时,通过ingest node,可以很方便的在新的index中获得不一样的mapping和value
POST _reindex
{"source": {"index": "source"},"dest": {"index": "dest","pipeline": "some_ingest_pipeline"}
}