在elasticsearch中,有时会想要通过索引日期来筛选查询的数据,此时就需要用到日期数学表达式。
更多内容参考Elasticsearch翻译汇总
基于日期数学表达式的索引
模式如下:
其中各个字段含义为:
static_name 是索引的静态部分
date_math_expr 是日期的表达式
date_format 格式化,默认是YYYY.MM.dd
time_zone 时区,默认是utc
需要注意的是,在使用时要把索引以及日期表达式的部分放在< >尖括号内。
日期数学表达式的例子
比如现在的时间是2024年3月22日中午12点.utc
注意,如果是中国的时间需要加上8个小时!
表达式
表示的值
test-2024.03.22
test-2024.03.01
test-2024.03
test-2024.02
test-2024.03.23
在数学日期表达式中,now就是现在的时间,比如,我写下这篇博客的时间是2016.03.17 20:39:00。
now/d,就是向一天取整,即2016.03.17 00:00:00。
now/M,就是向一个月取整,即2016.03.01 00:00:00
它还支持加减法,比如
now+1h,就是2016.03.17 21:39:00
now-1d,就是2016.03.16 20:39:00
了解日期表达式的用法,在使用elasticsearch时是很必要的。
索引数据的例子
curl -XPOST 'localhost:9200/
{
"_index" : "test-2016.03.01",
"_type" : "type",
"_id" : "1",
"_version" : 1,
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"created" : true
}
注意:
1 正常的日期表达式格式为 now/d,但是符号/必须经过编码才行
2 大括号需要进行转义
查询数据的例子
使用起来跟索引数据时一样。
curl -XPOST 'localhost:9200/
{
"took" : 120,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : 1.0,
"hits" : [ {
"_index" : "test-2016.03.01",
"_type" : "type",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"name" : "xing1",
"age" : 20
}
} ]
}
}
在所有带有index的API中,都支持上面的用法。
参考
1 官方文档:Date Math support in index names
精彩文章
发表评论