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指向了新的索引


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM