ES使用小结之索引Rollover

Elasticsearch 使用小结之索引Rollover

索引名

一般而言,客户端将数据每天写入一个索引,比如直接写入YYYY-MM-HH格式的索引,那么我们只需要在写入的客户端里面获取时间,然后得到相应的格式即可,例如logstash写入ES时索引名就是logstash-YYYY-MM-HH,但是实际使用中,我们总会遇到这种格式的索引名不太适用的情况(比如每天数据量很少,但是又需要保存很久的数据,或者每天数据量极大,每天一个索引已经不能容纳了),这个时候我们就需要考虑一个机制,将索引rollover,让我们能够按照具体情况调节写的索引。

索引别名-alias

ES提供了为索引创建别名的接口,例如:
POST _aliases 
{
    "actions" : [
        {
            "add" : {
                 "index" : "test_index",
                 "alias" : "test_alias",
                 "is_write_index" : true
            }
        }
    ]
}
这里就创建了一个alias指向test_index,在使用时,用test_alias替代操作即可对test_index进行操作。 

手动Rollover

结合alias,我们可以实现客户端写alias,在需要时将alias指向一个新的索引,就可以自由地控制数据的写入了。
步骤如下:
1. 先create一个新的索引
    PUT test_index2
2. 再将alias指向新的索引并移除旧的alias
    POST _aliases
    {
        "actions" : [
            {
                "remove" : {
                     "index" : "test_index",
                     "alias" : "test_alias",
                }
            },
            {
                "add" : {
                     "index" : "test_index2",
                     "alias" : "test_alias",
                     "is_write_index" : true
                }
            }
        ]
    }

自动Rollover

在上文中,我们手动Rollover了一个索引,在运行过程中,我们需要不断的获取ES中索引的情况,然后判断是否进行Rollover。这里,我们可以用ES自带的Rollover接口替代,假设已经存在一个test_index, 和一个test_alias指向test_index。
1.先执行一次rollover验证一下
POST test_alias/_rollover/test_index2
{
  "conditions": {
    "max_age":   "7d",
    "max_docs":  1
  }
}
Response:
{
  "old_index": "test_index",
  "new_index": "test_index2",
  "rolled_over": false,
  "dry_run": false,
  "acknowledged": false,
  "shards_acknowledged": false,
  "conditions": {
    "[max_docs: 1]": false,
    "[max_age: 7d]": false
  }
}
这个返回表明test_index没有触发我们传入的条件max_age存在7天或者max_docs文档数量达到1
2.写入一个doc
PUT test_alias/test/1
{
  "field1":"value"
}
3.再次执行rollover
POST test_alias/_rollover/test_index2
{
  "conditions": {
    "max_age":   "7d",
    "max_docs":  1
  }
}
Response:
{
  "old_index": "test_indexbb",
  "new_index": "test_indexcc",
  "rolled_over": true,
  "dry_run": false,
  "acknowledged": true,
  "shards_acknowledged": true,
  "conditions": {
    "[max_docs: 1]": true,
    "[max_age: 7d]": false
  }
}
触发了max_docs达到1的条件rollover成功,创建了新的索引并将test_alias指向了新的索引

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注