elasticsearch 当日按时间弹性查询

bqujaahr  于 7个月前  发布在  ElasticSearch
关注(0)|答案(2)|浏览(54)

我有一个查询,它获取我设置的日期的所有数据。这个查询到目前为止工作得很好。
当我删除日期并更改格式时,我以为弹性将采用当前日期,但没有。

**GET /BLA*/_search**
{
  "size" : 1,
  "sort" : "@timestamp",
  "_source" : ["@timestamp", "details"],
  "query" : {
    "bool" : {
      "must" : [
        {"term" : {"FIELD" : "TRUC"}},
        {"regexp" : { "details" : ".*TRUC.*" }},
        {"range": {
          "@timestamp": {
            "format" : "yyyy-MM-dd HH:mm",
            "from": "2020-05-05 07:00",
            "to": "2020-05-05 07:30",
            "time_zone" : "Europe/Paris"
          }
        }}
       ]
    }
  }
}

字符串
我试图删除日期并更改格式,但它不起作用。
目标是获取当天的数据。

**GET /BLA*/_search**
{
  "size" : 1,
  "sort" : "@timestamp",
  "_source" : ["@timestamp", "details"],
  "query" : {
    "bool" : {
      "must" : [
        {"term" : {"FIELD" : "TRUC"}},
        {"regexp" : { "details" : ".*TRUC.*" }},
        {"range": {
          "@timestamp": {
            "format" : "HH:mm",
            "from": "07:00",
            "to": "07:30",
            "time_zone" : "Europe/Paris"
          }
        }}
       ]
    }
  }
}

mrwjdhj3

mrwjdhj31#

TL;DR不可能。我所知道的在范围查询中使用w/ relative datetime的唯一方法是:

{
  "size": 1,
  "sort": "@timestamp",
  "_source": [
    "@timestamp",
    "details"
  ],
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "@timestamp": {
              "gte": "now-2h",
              "lte": "now+3h",
              "time_zone": "Europe/Paris"
            }
          }
        }
      ]
    }
  }
}

字符串
但都是相对于now
下面是为什么你的查询似乎不起作用的解释。
让我们设置一个索引,其@timestamp的格式为HH:mm

PUT my_index
{
  "mappings": {
    "properties": {
      "@timestamp": {
        "type": "date",
        "format": "HH:mm"
      }
    }
  }
}


然后服用一种

POST my_index/_doc
{
  "@timestamp": "07:00"
}


现在让我们来研究一下 * 实际 * 索引日期是什么:

GET my_index/_search
{
  "script_fields": {
    "ts_full": {
      "script": {
        "source": """
                  LocalDateTime.ofInstant(
                     Instant.ofEpochMilli(doc['@timestamp'].value.millis),
                     ZoneId.of('Europe/Paris')
                  ).format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"))
        """
      }
    }
  }
}


其产生

"01/01/1970 08:00:00"


因为巴黎是UTC+1。

所以总结一下,你肯定可以通过HH:mm的“日期”(严格来说是“时间”)来索引和搜索,但它们都与1970年1月1日有关。

hyrbngr7

hyrbngr72#

获取今天文件的时间

"query": {
    "bool": {
      "must": [
        {
          "range": {
            "@timestamp": {
              "gte": "now/d",
              "time_zone": "UTC"
            }
          }
        }
      ]
    }
  }

字符串

相关问题