1. 程式人生 > >Elasticsearch——Date Math在索引中的用法詳解

Elasticsearch——Date Math在索引中的用法詳解

在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-{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

  • 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中,都支援上面的用法。

參考