零停机更改 mapping(reindex + 原子别名切换)
Elasticsearch索引生命周期命令
# 1) Target index with the new mapping (refresh off and replicas 0 for loading):
PUT musteri-v2
{
"settings": { "number_of_shards": 1, "number_of_replicas": 0, "refresh_interval": "-1" },
"mappings": { "properties": { "kod": { "type": "keyword" }, "adet": { "type": "long" } } }
}
# 2) Reindex in the background (tracked with the returned task id):
POST _reindex?wait_for_completion=false&slices=auto
{
"source": { "index": "musteri-v1", "size": 1000 },
"dest": { "index": "musteri-v2", "op_type": "create" },
"conflicts": "proceed"
}
GET _tasks/<task_id>
# 3) Restore settings and compare document counts:
PUT musteri-v2/_settings
{
"index": { "refresh_interval": null, "number_of_replicas": 1 }
}
POST musteri-v2/_refresh
GET _cat/indices/musteri-v1,musteri-v2?v&h=index,docs.count,pri.store.size
# 4) Switch the alias to the new index in one atomic operation:
POST _aliases
{
"actions": [
{ "remove": { "index": "musteri-v1", "alias": "musteri" } },
{ "add": { "index": "musteri-v2", "alias": "musteri", "is_write_index": true } }
]
}作用
创建使用新 mapping 的索引,在后台用 reindex 复制数据,比较文档数,并在一次原子操作中将应用使用的别名切换到新索引。
适用场景
需要更改现有字段的类型(text -> keyword、integer -> long)、更改 analyzer 或重新定义分片数时;这些无法在现有索引上原地完成。
注意
应用必须连接别名而不是索引名;否则切换需要一次部署。reindex 期间写入源索引的新数据不会到达目标:要么停止写入,要么在切换前以 op_type create + conflicts proceed 重新运行 reindex 来弥补缺口(更新和删除不会以这种方式带过去)。reindex 会给源索引带来读负载、给目标索引带来写负载;用 requests_per_second 限流。