一個索引名同時匹配多個模板,套上的不是你想要的那個。根因是多個模板匹配時,
priority最高的模板被選;不設priority就按 0(最低)處理,多個 0 之間結果不可控。
Issue & Env(案發現場與環境)
- 業務場景:建了通用模板
logs_common(logs-*)和專用模板logs_error(logs-error-*),建logs-error-2026-01時想套logs_error,結果套成了logs_common。 - 環境:OpenSearch 3.x(Docker latest),單節點。
- 關鍵區分:兩個模板的
index_patterns都匹配logs-error-*,誰生效看priority。
StackTrace(返回體現狀)
建 logs-error-2026-01 後查 mapping,套的是通用模板的字段,不是專用模板的字段(無報錯,是套錯):
{
"logs-error-2026-01" : {
"mappings" : {
"properties" : {
"message" : { "type" : "text" }
}
}
}
}
本應套 logs_error 的 error_code、stack_trace 字段,結果套了 logs_common 的 message。
Reproduce(復現程式碼)
# ① 通用模板,没设 priority(默认 0)
curl -sk -u admin:Devfix@2026 -X PUT "https://localhost:9200/_index_template/logs_common?pretty" \
-H "Content-Type: application/json" \
-d '{ "index_patterns": [ "logs-*" ], "template": { "mappings": { "properties": { "message": { "type": "text" } } } } }'
# ② 专用模板,也没设 priority(默认 0)
curl -sk -u admin:Devfix@2026 -X PUT "https://localhost:9200/_index_template/logs_error?pretty" \
-H "Content-Type: application/json" \
-d '{ "index_patterns": [ "logs-error-*" ], "template": { "mappings": { "properties": { "error_code": { "type": "keyword" } } } } }'
# ③ 两个都匹配,priority 都是 0,套哪个不可控
curl -sk -u admin:Devfix@2026 -X PUT "https://localhost:9200/logs-error-2026-01?pretty"
判定標準:③ 套的模板不可控——因為兩個模板 priority 都是 0,選擇結果不確定。
Root Cause(根因分析)
多模板匹配時 priority 高的勝出
官方文檔明確:新索引匹配多個模板時,priority 最高的模板被選。不設 priority 就按 0(最低優先級)處理。兩個都 0,就沒法確定套哪個。
越具體的模板,priority 應該越高
正確做法是「越專用的模板給越高的 priority」:通用 logs-* 給低值(如 10),專用 logs-error-* 給高值(如 100)。這樣專用模板蓋過通用模板。
The Fix(解決方案)
第一步:給專用模板更高的 priority
curl -sk -u admin:Devfix@2026 -X PUT "https://localhost:9200/_index_template/logs_error?pretty" \
-H "Content-Type: application/json" \
-d '{ "index_patterns": [ "logs-error-*" ], "priority": 100, "template": { "mappings": { "properties": { "error_code": { "type": "keyword" } } } } }'
priority: 100 讓 logs_error 壓過 logs_common(priority 0),logs-error-* 的索引套專用模板。
第二步:重建索引套正確模板
模板不回頭改舊索引,重建或走零停機重建:
curl -sk -u admin:Devfix@2026 -X DELETE "https://localhost:9200/logs-error-2026-01?pretty"
curl -sk -u admin:Devfix@2026 -X PUT "https://localhost:9200/logs-error-2026-01?pretty"
注意事項
- priority 是數字,越大越優先;未指定視為 0。
- 多個模板的同名字段、settings 衝突時,也遵循優先級規則。
- 完整用法見 從零跑通 OpenSearch 索引模板與生命週期。
References(參考來源)
- Index templates — OpenSearch 官方文檔opensearch-docs
