在elasticsearch中,有时会想要通过索引日期来筛选查询的数据,此时就需要用到日期数学表达式。 更多内容参考Elasticsearch翻译汇总
模式如下:
<static_name{date_math_expr{date_format|time_zone}}>
其中各个字段含义为:
需要注意的是,在使用时要把索引以及日期表达式的部分放在< >
尖括号内。
比如现在的时间是2024年3月22日中午12点.utc
注意,如果是中国的时间需要加上8个小时!
表达式 | 表示的值 |
---|---|
<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.03.17 20:39:00
。
2016.03.17 00:00:00
。2016.03.01 00:00:00
它还支持加减法,比如
2016.03.17 21:39:00
2016.03.16 20:39:00
了解日期表达式的用法,在使用elasticsearch时是很必要的。
curl -XPOST 'localhost:9200/<test-\{now%2FM\}>/type/1?pretty' -d '{"name":"xing1",age:20}'
{
"_index" : "test-2016.03.01",
"_type" : "type",
"_id" : "1",
"_version" : 1,
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"created" : true
}
注意:
/
必须经过编码才行使用起来跟索引数据时一样。
curl -XPOST 'localhost:9200/<test-\{now%2FM\}>/_search?pretty' -d '{"query":{"match_all":{}}}'
{
"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中,都支持上面的用法。