在使用 Elasticsearch 举行数据存储和检索时,时间戳字段是一个非常重要的组成部分。它可以帮助我们追踪数据的创建或更新时间,便于后续的查询、分析和监控。Elasticsearch 提供了多种方式来自动为文档添加时间戳字段。本文将介绍怎样为索引设置自动的时间戳字段,并探讨相关的设置选项。
0、思绪
设置自动时间戳字段,可以思量 ES 的预处置惩罚功能,即 _ingest 的 pipline,在数据写入之前生成时间戳,写入到指定字段。
留意:
使用 pipeline 功能需要集群中有 ingest 的节点
即:node.roles: ingest
下面将介绍操作步调
1、设置 ingest pipeline
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 的管道,可以在索引模板,或者索引中声明使用。
2、在索引映射中启用_source字段的时间戳
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字段。
3、使用 index template 全局设置时间戳
当然,你也可以在 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 字段的映射。
4、写入测试数据
然后,在索引文档时指定该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"
- }
复制代码 5、验证结果
实行查询
结果如下:
6、总结
Elasticsearch提供了多种方式来自动为索引添加时间戳字段。你可以通过索引映射、ingest pipeline、index template等方式来实现这一功能。根据你的详细需求,选择合适的方法来确保时间戳字段的准确性和一致性。
通过公道设置时间戳字段,你可以更好地管理和分析数据,提升系统的可观测性和运维效率。希望本文对你明白和使用Elasticsearch的时间戳功能有所帮助!
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |