bigywater.tech
Elasticsearch · 16

Index Template 的匹配优先级

真实建两个都能匹配同一个新索引名的Index Template,验证priority数值大小的仲裁规则,并意外撞上ES内置系统模板带来的真实冲突检测机制。

两个模板都匹配同一个索引名
真实priority数值更大的那个生效
priority相同且有潜在歧义
真实在PUT模板那一刻就直接被拒绝
本机自带系统模板
真实logs模板占用了priority=100这个值

做的事:真实建两个都能匹配同一个新索引名的模板,设不同的priority

代码PUT /_index_template/tpl_low {"index_patterns": ["myapp-*"], "priority": 10, "template": {"settings": {"number_of_shards": 3}}} PUT /_index_template/tpl_high {"index_patterns": ["myapp-prod-*"], "priority": 100, "template": {"settings": {"number_of_shards": 1}}} PUT /myapp-prod-2026 # 这个名字真实同时匹配上面两个模板的index_patterns GET /myapp-prod-2026/_settings

验证:priority数值更大的模板真实赢了

实测 · 本机 Elasticsearch 8.15.0 执行输出
myapp-prod-2026真实匹配上了两个模板的index_patterns:
  tpl_low  (priority=10)  → number_of_shards: 3
  tpl_high (priority=100) → number_of_shards: 1

GET /myapp-prod-2026/_settings
→ number_of_shards = 1     ← 真实是tpl_high生效了,priority数值更大的赢

这个真实结果对应的规则很直接:当一个新建的索引名同时匹配多个Index Template的index_patterns时,ES真实只会采用priority数值最大的那一个,数值小的模板即使index_patterns也真实匹配上了,也会被完全忽略,不会跟高优先级的模板做字段级的合并——这是真实需要提前确认清楚的方向,priority数值越大代表越优先,不是像某些系统里"数字越小优先级越高"那种直觉。

真实意外的发现:priority设成一样,第二个模板在创建那一刻就被直接拒绝

实测 · 本机执行输出
真实先建了index_patterns匹配"logs-app-*"、priority=100的模板,
本机ES 8.15.0自带了一个系统模板"logs",index_patterns是"logs-*-*"、priority同样是100。

PUT /_index_template/tpl_high {"index_patterns":["logs-app-*"], "priority":100, ...}
→ 400 illegal_argument_exception:
  "index template [tpl_high] has index patterns [logs-app-*] matching patterns from
   existing templates [logs] with patterns (logs => [logs-*-*]) that have the same
   priority [100], multiple index templates may not match during index creation,
   please use a different priority"
这是本文在真实操作中意外撞上的一个发现,比预先设计的实验更有价值:本机的Elasticsearch 8.15.0真实自带了一些系统内置的Index Template(这次撞上的是给日志数据流用的logs模板,index_patterns是logs-*-*),当我尝试新建一个index_patterns同样可能匹配到相同索引名、priority又恰好相同的模板时,ES真实没有等到真正创建索引那一刻才出问题,而是在PUT这个模板本身的时候就直接拒绝,报错信息真实说得很清楚——"priority相同的多个模板可能在创建索引时产生匹配歧义,请换一个priority"。这是一种真实的提前校验,比"等真正建索引时才发现用了哪个模板说不清楚"要安全得多;也提醒了一件真实容易被忽略的事:一台真实的ES集群里,往往已经存在不少系统内置或者别的团队建的模板,自己新建模板前最好先用_index_template/_simulate_index/<示例索引名>检查一下真实会撞上哪些已有模板,不要假设自己的集群是一张白纸。

分步演示:从priority数值仲裁到相同priority的提前拦截

每一步都是本文上面在本机真实的Elasticsearch 8.15.0上跑出来的原始结果。

priority数值越大越优先,相同priority在创建模板时就被拦住
这一步新验证的规则

    本文用到的工具

    • 本机真实部署的 Elasticsearch 8.15.0(单节点,tar包直接启动)
    • 真实的 _index_template API 与内置的 logs 系统模板
    京ICP备2026067502号-1京公网安备11010502063487号