如何基于 ingest timestamp 而非 @timestamp 自定义 ILM 时间

解读

国内生产环境普遍要求“日志可审计、索引生命周期可回溯”。面试官问“能不能不用 @timestamp 而用 ingest 时间做 ILM 滚动依据”,核心想验证三点:

  1. 你是否清楚 ILM 在“热温冷删”各阶段到底读哪个字段;
  2. 能否绕过 Elastic 默认的“@timestamp 优先”逻辑,避免业务时间错填导致提前删除或无限保留;
  3. 是否具备“不改业务代码、不改已有模板”的在线改造能力,因为国内互联网场景往往“先上线后治理”,不能停写。

一句话:把 ILM 的“时间锚点”从业务字段换成 ingest 时刻,并保证新老索引平滑过渡。

知识点

  1. ILM 的“时间戳来源”优先级:
    如果索引设置 index.lifecycle.parse_origination_date: true,ES 会优先尝试从索引名提取日期;未配置时默认用“索引创建时间”作为 age 条件基准,与文档内的 @timestamp 无关。
  2. ** ingest 时间的位置**:
    ingest pipeline 默认注入的 _ingest.timestamp 仅存在于 pipeline 上下文,不会自动写入文档字段,因此不能被 ILM 直接读取。
  3. “reroute trick”:
    在 pipeline 里用 set 处理器把 _ingest.timestamp 复制到一个新字段(如 ingest_time),然后让 ILM 通过 index.lifecycle.origination_date 指向该字段的数值毫秒值,即可实现“文档级 ingest 时间驱动”。
  4. 国内集群常见限制:
    • 7.10 以后阿里云、腾讯云托管版禁用了 index.metadata 的自定义属性写入,因此不能靠 index.meta.ingest_time 存值;
    • 必须走索引模板 + component template 方式,把 origination_date 预埋在 settings 里,避免运行时 PUT /_settings 被平台拦截。

答案

步骤如下,全部在线完成,无需重启节点或暂停写入:

  1. 新建 component template,注入 ingest pipeline 并预定义 settings:

    PUT _component_template/ingest_time_ct
    {
      "template": {
        "settings": {
          "index.lifecycle.name": "log_ilm_policy",
          "index.lifecycle.parse_origination_date": true,
          "index.lifecycle.origination_date": "{{_ingest.timestamp}}"
        },
        "mappings": {
          "properties": {
            "ingest_time": { "type": "date", "format": "epoch_millis" }
          }
        }
      }
    }
    
  2. 在 pipeline 里把 _ingest.timestamp 落地到文档,并同步回填 settings:

    PUT _ingest/pipeline/set_ingest_time
    {
      "processors": [
        {
          "set": {
            "field": "ingest_time",
            "value": "{{_ingest.timestamp}}"
          }
        },
        {
          "script": {
            "source": """
              ctx['_index']['settings']['index']['lifecycle']['origination_date'] = ctx['ingest_time'];
            """
          }
        }
      ]
    }
    
  3. 创建索引模板,关联 component template 与 pipeline:

    PUT _index_template/log_data
    {
      "index_patterns": ["log-*"],
      "composed_of": ["ingest_time_ct"],
      "template": {
        "settings": {
          "default_pipeline": "set_ingest_time"
        }
      },
      "priority": 200
    }
    
  4. 滚动写新索引(rollover)后,ILM 的 min_age 将以 ingest_time 对应的毫秒值作为起点计算,与 @timestamp 完全解耦。老索引若无 origination_date 则继续用“索引创建时间”兜底,实现新老共存、平滑过渡。

拓展思考

  1. 时区与 Daylight Saving:
    ingest 时间默认 UTC,若业务报表需按“北京时间 T+1 删除”,要在 pipeline 里用 script 把 ingest_time + 8h 后再回填,否则 00:00-08:00 的数据会被多留一天。
  2. 性能与存储成本:
    每文档多存一个 long 型字段,PB 级集群膨胀约 2.3%,可通过 index.codec: best_compression 抵消;若只关心索引级滚动,可改为在rollover 请求里手动携带 ?origination_date={now_millis},省去字段存储。
  3. 合规审计:
    金融、政企项目要求“不可抵赖”,可把 _ingest.timestamp 同时写入 ingest_time 与 _source 外的 meta 字段,并开启 index.soft_deletes.enabled=true,配合 searchable snapshot 实现“写入即归档”,满足等保 2.0 关于日志留存 6 个月以上的条款。