elasticsearch使用索引模板和别名高效地处理日志类索引

10月 27, 2016 |

使用elasticsearch存储日志在互联网企业是一个很常见的应用。虽然elastic公司提供成熟的logstash,自己实现也不难。
如果将所有的文档存放在一个索引中,那么清除陈旧的文档时很耗资源,需要先查询出待删除的ID,然后调用删除命令,其实在底层,elasticsearch根本没有释放被删除的这些文档占用的磁盘资源,只是将其标记为已删除,只有等到下次merge的时候才会真正的释放占用的磁盘资源,众所周知,索引merge是一个巨耗资源的操作。
思路如下:每月1号凌晨定时创建索引,然后将logs_current别名指向新的索引,logs_current用于新增和更新索引,将last_3_months指向最近三个月的索引,用于查询。这时就可以释放掉陈旧索引所占用的资源了。而且很高效。

1、创建索引模板

{
"template" : "logs_*",
"mappings" : {
"logs_type" : {
"properties" : {
"id" : {
"type" : "string"
},
"content" : {
"type" : "string"
},
"timestamp" : {
"type" : "string",
"index" : "not_analyzed"
}
}
}
}
}

最好将其存储为一个文件。便于编辑,假设命名为logs_template.json
然后执行如下命令将模板添加到elasticsearch

curl -XPUT localhost:9200/_template/logs_template -d @~/logs_template.json

2、定时任务中创建新的索引,更新别名的指向,删除陈旧的索引

在定时任务脚本中,使用如下的shell命令查看待操作的索引是否存在

CURRENT_MONTH_EXISTS=$(curl -I -s -o /dev/null -w "%{http_code}" "${URL}/logs_${CURRENT_MONTH}")

创建空索引,而不添加数据

curl -XPOST "${URL}/vst_log_${CURRENT_MONTH}"

创建别名

curl -XPOST "http://localhost:9200/_aliases"
{
"actions": [
{ "add": { "alias": "logs_current", "index": "logs_2014-10" }},
{ "remove": { "alias": "logs_current", "index": "logs_2014-09" }},
{ "add": { "alias": "last_3_months", "index": "logs_2014-10" }},
{ "remove": { "alias": "last_3_months", "index": "logs_2014-07" }}
]
}

删除陈旧的索引

curl -XDELETE "${URL}/logs_${TREE_MONTH_BEFORE}"

参考文档

官方文档:创建基于时间的索引
官方文档:索引模板

Posted in: ElasticSearch

Comments are closed.