reindex 時把
source和dest寫成同一個索引,直接報錯。根因是 reindex 的源和目標必須不同——它不能「原地重建」,必須遷到一個新的目標索引。這也是零停機重建要「建新索引 v2 → reindex 遷過去 → 別名切換」的原因。
Issue & Env(案發現場與環境)
- 業務場景:想給
movies索引重建(比如改了分析器想重跑一遍),圖省事把 reindex 的 source 和 dest 都寫成movies,結果報錯。 - 環境:OpenSearch 3.x(Docker latest),單節點。
- 關鍵區分:reindex 不是「原地重算」,是「從 A 複製到 B」。
StackTrace(報錯原文)
{
"error" : {
"type" : "illegal_argument_exception",
"reason" : "reindex doesn't support the [same index] as the source and destination index"
}
}
Reproduce(復現程式碼)
# source 和 dest 都是 movies → 报错
curl -sk -u admin:Devfix@2026 -X POST "https://localhost:9200/_reindex?pretty" \
-H "Content-Type: application/json" \
-d '{ "source": { "index": "movies" }, "dest": { "index": "movies" } }'
判定標準:返回 reindex doesn't support the same index 錯誤。
Root Cause(根因分析)
reindex 是「複製」,不是「原地重建」
reindex 從源索引讀 _source,逐條寫進目標索引。如果源和目標相同,讀和寫會互相干擾(讀一條寫一條,又可能被自己讀回來),邏輯上就不成立。官方文檔明確:source 和 destination 必須不同。
目標索引要提前建
reindex 不會自動複製源索引的 settings/mappings。目標索引必須先創建並配好想要的 mapping/settings,reindex 只負責搬數據。這也解釋了為什麼改分析器/改 mapping 的正確姿勢是「建新索引 → reindex → 別名切換」,而不是原地改。
The Fix(解決方案)
第一步:先建目標索引(帶新 mapping)
curl -sk -u admin:Devfix@2026 -X PUT "https://localhost:9200/movies_v2?pretty" \
-H "Content-Type: application/json" \
-d '{ "mappings": { "properties": { "title": { "type": "text", "analyzer": "standard" }, "year": { "type": "integer" } } } }'
第二步:reindex 從舊遷到新
curl -sk -u admin:Devfix@2026 -X POST "https://localhost:9200/_reindex?pretty" \
-H "Content-Type: application/json" \
-d '{ "source": { "index": "movies" }, "dest": { "index": "movies_v2" } }'
第三步:別名切到新索引(零停機)
見 從零跑通 OpenSearch 索引別名與零停機重建 的 Index swapping 步驟。
注意事項
- reindex 要求源索引的
_source啟用(預設啟用)。 - 大索引 reindex 可臨時把目標索引
number_of_replicas設為 0 加速,完了再調回。 - 完整用法見 從零跑通 OpenSearch 索引別名與零停機重建。
References(參考來源)
- Reindex documents API — OpenSearch 官方文檔opensearch-docs
