Elasticsearch 滚动索引创建指南
1. 创建生命周期策略(ILM Policy)
定义索引的生命周期规则,如滚动更新(Rollover)、删除等。
bash复制
PUT _ilm/policy/testlog-html-template
{
"policy": {
"phases": {
"hot": {
"actions": {
"rollover": {
"max_size": "50GB",
"max_age": "30d",
"max_docs": 10000
}
}
},
"delete": {
"min_age": "90d",
"actions": {
"delete": {}
}
}
}
}
}
max_size
:索引达到的最大大小。max_age
:索引的最大年龄。max_docs
:索引的最大文档数。min_age
:索引在删除之前需要达到的最小年龄。
2. 创建索引模板(Index Template)
模板自动应用到新创建的索引,绑定生命周期策略和别名。
bash复制
PUT _index_template/testlog-html-template
{
"index_patterns": ["testlog-html-*"],
"template": {
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1,
"index.lifecycle.name": "testlog-html",
"index.lifecycle.rollover_alias": "testlog-html"
},
"aliases": {
"testlog-html": {}
},
"mappings": {
"properties": {
"@timestamp": { "type": "date" },
"message": { "type": "text" }
}
}
}
}
index_patterns
:匹配的索引名称模式。index.lifecycle.name
:绑定的生命周期策略名称。index.lifecycle.rollover_alias
:滚动更新时使用的别名。
3. 创建初始索引(如 my-index-000001
)
手动创建第一个索引,并标记为可写入的别名。
bash复制
PUT testlog-html-000001
{
"aliases": {
"testlog-html": {
"is_write_index": true
}
}
}
is_write_index
:标记为写入索引,所有写入操作会路由到该索引。
4. 验证与触发滚动
当满足 rollover
条件(如时间、文档数、大小)时,Elasticsearch 会自动创建新索引(如 my-index-000002
),并将别名切换到新索引。
手动触发 Rollover(可选)
bash复制
POST /testlog-html/_rollover
{
"conditions": {
"max_age": "30d",
"max_docs": 10000
}
}
conditions
:手动指定触发滚动的条件。
关键点说明
- 别名(Alias):应用程序通过别名
my-alias
读写数据,无需感知底层索引变化。 - 生命周期管理(ILM):自动根据策略滚动、迁移或删除旧索引。
- 索引模板:确保新索引继承一致的配置(如分片、映射、生命周期绑定)。
总结流程图
plaintext复制
创建 ILM 策略 → 创建索引模板 → 创建初始索引(绑定别名) → 自动滚动新索引