
我将数据索引到 Elasticsearch ,会出现数据丢失的情况,比如写入100w,实际索引的文档可能90w。因为是开发环境,ES 只有单个节点,服务器也只有 4G 内存,多次尝试无果,只好另辟蹊径。我在一台配置好的服务器上搭建了一个ES 节点,先把数据索引到该节点,再使用 reindex 将数据迁移到我的开发服务器。
reindex 有两种
本地:https://www.elastic.co/guide/en/elasticsearch/reference/current/reindex-upgrade-inplace.html
远程:https://www.elastic.co/guide/en/elasticsearch/reference/current/reindex-upgrade-remote.html
下面以远程索引重建为例,记录一下大概的步骤
1. 新ES集群中,将老集群添加到白名单。在 elasticsearch.yml 中添加如下
reindex.remote.whitelist: oldhost:9200
重启 Elasticsearch 服务
2. 在新集群中,创建索引,并将 refresh_interval 设为 -1,number_of_replicas 设为 0
PUT index_name/_settings?pretty
{
"index.refresh_interval": -1,
"index.number_of_replicas": 0
}
3. 使用 reindex api 将文档从远程拉取到新的集群
POST _reindex
{
"source": {
"remote": {
"host": "http://oldhost:9200",
"username": "user",
"password": "pass"
},
"index": "source",
"query": {
"match": {
"test": "data"
}
}
},
"dest": {
"index": "dest"
}
}
通过将wait_for_completion 设为 false,可以将 reindex 在后台运行
POST _reindex?wait_for_completion=false
这是 reindex 会返回一个 task_id

根据这个 task_id 可以监控 reindex 的进度
GET _tasks/task_id
4. 当 reindex 完成,再将 refresh_interval 和 number_of_replicas 设为期望的值(默认值分别为 30s 和 1)
5. 新的索引状态为 green 后,就可以删除老的索引了。