时间分区API使用

Lindorm搜索引擎支持时间分区(Data Stream)功能,用户可通过API接口完成时间分区的创建、读写和删除操作。时间分区适用于写入和查询都带有时间戳字段的场景。比如日志场景,按时间序列生成日志数据写入到数据库,支持高效查询特定时间范围内的日志。

前提条件

搜索引擎为3.9.33及以上版本,如何升级当前版本,请参见升级小版本

时间分区读写原理

  • 写入:根据业务指定的时间戳,写入到对应的后台索引中。

  • 查询:根据查询的时间戳范围,路由到对应的后台索引查询;若无时间戳条件,则执行全局索引查询。

image

创建索引模板

Lindorm的时间分区功能使用天为单位的interval参数(基于UTC时区),最小值为1天。创建分区时,系统会根据起始时间(start)和间隔(interval)自动计算需创建的后台索引数量。建议避免设置过小的interval值,否则可能因生成大量索引而导致分区创建操作耗时显著增加。

代码示例

PUT _index_template/tp-test
{
  "index_patterns": "tp-test",
  "data_stream": {
    "timestamp_field": {
      "name": "createTime"
    }
  },
  "template": {
    "settings": {
      "number_of_shards": 4,
      "index.mode": "time_partition",
      "index.partition.start": "10d",
      "index.partition.interval": "30d",
      "index.partition.ttl": "360d"
    }
  }
}

参数说明

参数名称

说明

index_patterns

必选参数:名称需与后面创建时间分区的名称相同

timestamp_field

指定用于时间分区的field,如:createTime,表示后续写入时,必须有createTime名称字段。

number_of_shards

指定每个索引的shard数量。

index.mode

默认设置为time_partition, 表示创建时间分区模式。

index.partition.start

必选参数,表示从当前多少天前开始创建分区,例如:10d 表示从10天前开始创建。

index.partition.interval

必选参数,表示每个分区的时间跨度,例如 30d,表示每隔30天创建一个分区。

index.partition.ttl

非必选参数:表示过期时间,默认永不过期;360d 表示 360天之前的数据会清理掉,释放空间。

创建时间分区

创建时间分区,会根据名称自动使用前面创建的索引模板配置。

重要

时间分区名称需与索引模板的index_patterns名称相同。

代码示例

PUT _data_stream/tp-test

写时间分区

写入数据的createTime需满足index.partition.start ~ index.partition.future时间范围,默认start时间之前的所有数据会写入0号时间分区。

代码示例

POST tp-test/_bulk
{ "index" : { "_id": 10} }
{ "createTime" : "2024-08-01T15:38+0800", "storeId" : 100 }
{ "index" : { "_id": 11} }
{ "createTime" : "2024-08-02T15:39+0800", "storeId" : 200 }

查询时间分区

通过时间范围查询数据。

代码示例

GET tp-test/_search
{
  "query": {                     
    "range": {
      "createTime": {
          "gte" : "2024-03-11T06:00:00",
          "lt" :  "2024-08-06T12:00:00"
      }
    }             
  }            
}

删除时间分区

根据名称删除时间分区。

代码示例

DELETE _data_stream/tp-test

查看索引模板

查看某个索引模板。

代码示例

GET _index_template/tp-test

查看时间分区配置

根据名称查看时间分区配置。

代码示例

GET _data_stream/tp-test

修改时间分区配置

支持修改时间分区的配置参数。

说明

index.partition.start暂不支持修改。

代码示例

以下代码以修改参数index.partition.ttlindex.partition.future为例。

PUT _data_stream/tp-test/_settings
{
    "index.partition.ttl": "30d"
}

PUT _data_stream/tp-test/_settings
{
    "index.partition.future": "5d"
}