目录

Elasticsearch为索引设置自动时间戳,ES自动时间戳

Elasticsearch为索引设置自动时间戳,ES自动时间戳

在使用 Elasticsearch 进行数据存储和检索时,时间戳字段是一个非常重要的组成部分。它可以帮助我们追踪数据的创建或更新时间,便于后续的查询、分析和监控。Elasticsearch 提供了多种方式来自动为文档添加时间戳字段。本文将介绍如何为索引设置自动的时间戳字段,并探讨相关的配置选项。

设置自动时间戳字段,可以考虑 ES 的预处理功能,即 _ingest 的 pipline,在数据写入之前生成时间戳,写入到指定字段。

注意:

使用 pipeline 功能需要集群中有 ingest 的节点

即:node.roles: ingest

下面将介绍操作步骤

Elasticsearch 的 ingest pipeline 功能允许你在数据索引之前对其进行处理。可以使用 set 处理器来添加时间戳字段。

以下涉及两个 processor,分别是 set processor和 date processor

首先,创建一个 ingest pipeline:

PUT _ingest/pipeline/pip_timestamp
{
  "processors": [
    {
      "set": {
        "field": "@timestamp",
        "value": "{{_ingest.timestamp}}",
        "override": true
      }
    },
    {
      "date": {
        "field": "@timestamp",
        "formats": ["yyyy-MM-dd HH:mm:ss","ISO8601"],
        "target_field": "@timestamp",
        "output_format": "yyyy-MM-dd HH:mm:ss",
        "timezone": "Asia/Shanghai"
      }
    }
  ]
}

上述代码创建了一个名为 pip_timestamp 的管道,可以在索引模板,或者索引中声明使用。

Elasticsearch 允许在索引映射中启用时间戳功能。可以在创建索引时,通过定义映射来启用自动时间戳字段。

PUT /my_index
{
  "settings": {
    "index":{
      "default_pipeline":"pip_timestamp"
    }
  }, 
  "mappings": {
    "properties": {
      "@timestamp": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
      },
      "message": {
        "type": "text"
      }
    }
  }
}

在这个例子中,我们定义了一个@timestamp字段,类型为 date。当你向该索引插入文档时,Elasticsearch会自动为每个文档生成一个@timestamp字段。

当然,你也可以在 Index_template 中定义声明,关于 pipline 的用法此处不再赘述。

如果你希望为多个索引自动添加时间戳字段,可以使用 index template。通过定义一个索引模板,你可以确保所有匹配该模板的索引都自动启用时间戳功能。

PUT _index_template/my_template
{
  "index_patterns": ["my_index*"],
  "template": {
    "mappings": {
      "properties": {
        "@timestamp": {
          "type": "date"
        }
      }
    },
    "settings": {
      "index.default_pipeline": "pip_timestamp"
    }
  }
}

在这个例子中,我们创建了一个名为 my_template 的索引模板,匹配所有以my_index 开头的索引。模板中指定了默认的 ingest pipeline 为pip_timestamp,并定义了@timestamp 字段的映射。

然后,在索引文档时指定该pipeline:

POST my_index/_doc
{
  "message":"test_content"
}

在这个例子中,{ {_ingest.timestamp}} 是一个动态变量,表示当前时间。Elasticsearch 会在索引文档时自动将当前时间戳添加到 @timestamp 字段。

POST /my_index/_doc?pipeline=pip_timestamp
{
  "message": "This is a test message"
}

执行查询

GET my_index/_search

结果如下:

https://i-blog.csdnimg.cn/direct/d07bc903a7224901867e34244951ac48.png#pic_center

Elasticsearch提供了多种方式来自动为索引添加时间戳字段。你可以通过索引映射、ingest pipeline、index template等方式来实现这一功能。根据你的具体需求,选择合适的方法来确保时间戳字段的准确性和一致性。

通过合理配置时间戳字段,你可以更好地管理和分析数据,提升系统的可观测性和运维效率。希望本文对你理解和使用Elasticsearch的时间戳功能有所帮助!