索引设计原则与模板
本章定位:索引模板(Index Template)让新创建的索引自动应用统一的 Settings 和 Mappings。别名(Alias)实现了索引的零停机切换。二者是生产环境索引管理的基石。
定义与作用
索引模板(Index Template):预定义一组 Settings 和 Mappings 规则,匹配该模板的索引在创建时自动应用这些规则。 别名(Alias):为索引或索引组创建一个逻辑名称,客户端通过别名读写,底层索引可以无缝切换。
完整示例:飞翔科技的索引管理
索引模板
PUT /_index_template/logs_template
{
"index_patterns": ["logs-*"],
"priority": 200,
"template": {
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1,
"refresh_interval": "30s"
},
"mappings": {
"dynamic": "strict",
"properties": {
"timestamp": { "type": "date" },
"level": { "type": "keyword" },
"message": { "type": "text" }
}
}
}
}
别名切换
POST /_aliases
{
"actions": [
{ "remove": { "index": "courses_v1", "alias": "courses" } },
{ "add": { "index": "courses_v2", "alias": "courses" } }
]
}
Component Template 复用
PUT /_component_template/common_settings
{ "template": { "settings": { "number_of_replicas": 1 } } }
PUT /_index_template/course_template
{
"index_patterns": ["course-*"],
"composed_of": ["common_settings", "ik_mapping"],
"priority": 100
}
小结
Index Template 确保索引创建一致性,Component Template 实现组件化复用。Alias 是零停机部署的核心武器——原子切换实现无感知索引迁移。