一个索引名同时匹配多个模板,套上的不是你想要的那个。根因是多个模板匹配时,
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
