StackTraces
OpenSearch已驗證

OpenSearch 索引套錯模板:多模板匹配時靠 priority 定優先級

@debug_master今天更新閱讀 6 min適用 [email protected]00

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

注意事項

References(參考來源)

最後更新於 2026-11-30

這篇幫到你了嗎?

剛解決了一個棘手的報錯?花兩分鐘記錄下來,幫助下一個遇到同樣問題的開發者。

貢獻一條解法