第四阶段 34 · 索引模板与 data stream(自动套 mapping / 时序数据)

📅 发布时间:2026/8/3 16:53:44
第四阶段 34 · 索引模板与 data stream(自动套 mapping / 时序数据) 34 · 索引模板与 data stream自动套 mapping / 时序数据阶段第四阶段 / 写入与索引管理ESindex template / component template / data stream | PostgreSQLCREATE TABLE ... LIKE模板 分区表1. 概念前面第 33 篇是「手动建一个索引」。但真实场景里索引常常是动态创建的按天/按月滚动如logs-2026.08.01你不可能每次手写 mapping。index template索引模板预先定义「索引名匹配某模式时自动套用哪套 settings/mappings」。新索引一创建就自动带上正确结构。component template组件模板可复用的 mapping/settings 片段多个索引模板拼装它避免重复。data stream数据流面向只追加的时序数据日志、指标、事件的高级抽象——你只对一个名字写入底层自动滚动出一串隐藏索引配合 ILM 自动管理生命周期。2. PostgreSQL 对照ESPostgreSQLcomponent template可复用的列定义 /LIKE table INCLUDING ALLindex template「新表自动套用某结构」的约定data stream分区表按时间自动路由到子分区只追加rollover分区滚动新月份自动进新分区3. ES DSL3.1 组件模板可复用片段PUT _component_template/base_settings { template: { settings: { number_of_shards: 1, number_of_replicas: 1 } } } PUT _component_template/sales_mappings { template: { mappings: { properties: { record_id: { type: keyword }, amount: { type: double }, timestamp: { type: date } } } } }3.2 索引模板匹配索引名拼装组件PUT _index_template/sales_template { index_patterns: [sales-*], // 索引名匹配 sales-* 就套用 composed_of: [base_settings, sales_mappings], priority: 200, // 多模板命中时取优先级高的 template: { aliases: { sales: {} } // 顺便挂别名 } }之后任何sales-2026.08之类的新索引一写入就自动带上上面的结构和别名。3.3 data stream时序只追加# 模板里声明这是 data stream 模板 PUT _index_template/logs_template { index_patterns: [logs-*], data_stream: {}, composed_of: [base_settings], priority: 200 } # 直接往 data stream 写必须带 timestamp POST logs-app/_doc { timestamp: 2026-08-01T10:00:00Z, level: INFO, msg: started } # 手动滚动通常交给 ILM 自动做 POST logs-app/_rolloverdata stream 只支持create追加不能像普通索引那样对历史文档随意update/delete要改走_update_by_query第 32 篇。4. Spring Boot 实现ComponentpublicclassDoc34Template{AutowiredprivateElasticsearchClientelasticsearchClient;/** 建/更新索引模板mapping 外置成 JSON用 withJson 直灌对照第 09 篇 */publicvoidputIndexTemplate(Stringname,StringtemplateJson)throwsIOException{PutIndexTemplateRequestreqPutIndexTemplateRequest.of(b-b.name(name).withJson(newStringReader(templateJson)));// 整段模板 DSL 直灌booleanokelasticsearchClient.indices().putIndexTemplate(req).acknowledged();if(!ok){thrownewIllegalStateException(put index template 失败: name);}}/** 对 data stream 手动触发一次 rollover一般由 ILM 自动完成 */publicvoidrollover(StringdataStream)throwsIOException{elasticsearchClient.indices().rollover(r-r.alias(dataStream));}}importco.elastic.clients.elasticsearch.indices.PutIndexTemplateRequest。模板 JSON 外置到resources/es-template/*.json改结构不必改 Java同第 09 篇思路。5. 坑与最佳实践模板只对“之后创建的索引”生效改了模板不会回改已存在的索引。priority决多模板冲突索引名同时命中多个模板时取priority最高的那个不叠加。data stream 必须有timestamp这是它排序/滚动的依据。data stream 配 ILM 才完整滚动、降副本、迁冷、删除交给 ILM 自动做见运维篇/官方 ILM。优先用 component template 拆公共片段多索引共享 settings/mapping避免复制粘贴漂移。别用旧的_templatelegacy8.x 用_index_template_component_template。