elasticesearch 第8章 数据迁移 elasticesearch 第8章 数据迁移

9小时前

Elasticsearch 数据迁移主要取决于数据量大小和集群版本跨度。

常见的方法包括:快照备份(海量数据首选)、Reindex API(同集群或跨小版本迁移)以及 Logstash/Elasticsearch-dump(轻量级或跨大版本同步)。

一、跨大版本 / 轻量级迁移

elasticsearch-dump

适用场景:数据量较小(GB级以内),或需灵活筛选特定数据。

优缺点:操作简单,支持跨大版本迁移(如5.x迁移至7.x/8.x);但速度较慢,容易中断。

操作命令(通过 npm 安装执行):

# 1. 全局安装 elasticdump 工具
npm install elasticdump -g

# 2. 迁移 Index 的 Settings
elasticdump --input=http://源IP:9200/源索引名 --output=http://目标IP:9200/目标索引名 --type=settings

# 3. 迁移 Index 的 Mapping
elasticdump --input=http://源IP:9200/源索引名 --output=http://目标IP:9200/目标索引名 --type=mapping

# 4. 迁移 Data 数据
elasticdump --input=http://源IP:9200/源索引名 --output=http://目标IP:9200/目标索引名 --type=data

二、同版本 / 跨小版本

Reindex API

适用场景:同一集群内迁移数据,或小版本之间迁移(如 6.x 到 7.x),不支持跨大版本(如 5.x 到 8.x)。

优缺点:无需停机,数据同步速度快,能自动处理 mapping 转换,支持指定查询条件迁移。

操作步骤:

①、配置白名单:在目标集群的 elasticsearch.yml 中添加 reindex.remote.whitelist: ["源集群IP:9200"]。

②、执行迁移命令(在 Kibana 中运行):

POST _reindex
{
 "source": {
   "remote": {
     "host": "http://源集群IP:9200",
     "username": "源集群用户名",
     "password": "源集群密码"
   },
   "index": "源索引名",
   "query": {
     "match_all": {}
   }
 },
 "dest": {
   "index": "目标索引名"
 }
}

三、海量数据首选:快照与恢复

Snapshot & Restore

适用场景:PB / TB 级别海量数据迁移。

优缺点:性能损耗极低,支持全量备份与按需恢复;要求两端集群版本必须兼容(低版本可以恢复至高版本,跨大版本需通过中间版本)。

操作步骤:

①、注册快照仓库:源集群和目标集群都需注册仓库。如使用本地共享文件,需修改 path.repo 配置;云端通常使用对象存储(如阿里云OSS、AWS S3),需安装对应的 Repository 插件(如 elasticsearch-repository-oss)。

PUT _snapshot/my_backup
{
 "type": "fs",
 "settings": {
   "location": "/mount/backups/my_backup"
 }
}

②、创建快照(源集群操作)

PUT _snapshot/my_backup/snapshot_1?wait_for_completion=true

③、恢复快照(目标集群操作)

POST _snapshot/my_backup/snapshot_1/_restore

四、复杂 ETL / 增量同步

Logstash

适用场景:实时同步增量数据、需要清洗/过滤或异构数据源迁移。

优缺点:支持实时、并发同步,高度可配置;需要搭建并配置 Logstash 运行环境。

操作指令(配置文件示例 es_to_es.conf):

input {
 elasticsearch {
   hosts => ["源集群IP:9200"]
   index => "源索引名"
   query => '{ "query": { "match_all": {} } }'
 }
}
output {
 elasticsearch {
   hosts => ["目标集群IP:9200"]
   index => "目标索引名"
 }
}


阅读 10