在elasticsearch中,有時會想要通過索引日期來篩選查詢的資料,此時就需要用到日期數學表達式。
更多内容參考Elasticsearch翻譯彙總
基于日期數學表達式的索引
模式如下:
<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
注意,如果是中國的時間需要加上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/<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
}
注意:
- 1 正常的日期表達式格式為 now/d,但是符号
必須經過編碼才行/
- 2 大括号需要進行轉義
查詢資料的例子
使用起來跟索引資料時一樣。
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中,都支援上面的用法。
參考
1 官方文檔:Date Math support in index names
作者:xingoo
出處:http://www.cnblogs.com/xing901022
本文版權歸作者和部落格園共有。歡迎轉載,但必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接!