Elasticsearch--Date math在索引中的使用
在Elasticsearch,有时要通过索引日期来筛选某段时间的数据,这时就要用到ES提供的日期数学表达式
描述:
特别在日志数据中,只是查询一段时间内的日志数据,这时就可以使用日期数学表达式,这样可以限制检索的索引数量,减少集群的负载,提高系统性能。
几乎所有的API都支持日期索引中的数学参数值。
基于日期数学表达式的索引:
<static_name{date_math_expr{date_format|time_zone}}>
其中各个字段的含义是:
static_name:索引名字的静态部分
date_math_expr:动态的日期表达式
date_format:格式化,默认是YYYY.MM.dd
time_zone:时区,默认是UTC
需要注意的是,在使用时要把索引以及日期表达式的部分放在<>
尖括号内。
日期数学表达式的例子
比如现在的时间是2024年3月22日中午12点.utc
表达式 |
表达式的值 |
<test-{now/d}> |
test-2024.03.22 |
<test-{now/M}> |
test-2024.03.01 |
<test-{now/M{YYYY.MM}}> |
test-2024.03 |
<test-{now/M-1M{YYYY.MM}}> |
test-2024.02 |
<test-{now/d{YYYY.MM.dd\|+12:00}}> |
test-2024.03.23 |
在数学日期表达式中,now就是现在的时间2016.05.09 14:11:26
- now/d,就是向一天取整,即2016.05.09 00:00:00.
- now/M,就是向一个月取整,即2016.05。01 00:00:00
它还支持加减法,比如:
- now+1h,就是2016.05.09 14:14:23
- now-1d,就是2016.05.09 14:15:04
索引数据的例子
curl -XPOST '192.168.204.32:9200/<test-\{now%2FM\}>/type/1?pretty' -d '{"name":"xing1",age:20}'‘ { "_index" : "test-2016.05.01", "_type" : "type", "_id" : "1", "_version" : 1, "_shards" : { "total" : 2, "successful" : 2, "failed" : 0 }, "created" : true }
注意:
- 1 正常的日期表达式格式为now/d,但是
/
必须经过编码也就是%2F
- 2 这里面所用到的大括号也要进行转义才行
查询数据的例子
# curl -XPOST '192.168.204.42:9200/<test-\{now%2FM\}>/_search?pretty' -d '{"query":{"match_all":{}}}' { "took" : 3, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "failed" : 0 }, "hits" : { "total" : 1, "max_score" : 1.0, "hits" : [ { "_index" : "test-2016.05.01", "_type" : "type", "_id" : "1", "_score" : 1.0, "_source" : { "name" : "xing1", "age" : 20 } } ] } }
几本上所有api索引参数,支持日期索引中数学参数值。
参考
好的代码像粥一样,都是用时间熬出来的