Elasticsearch 在映射时更改日期格式

Elasticsearch change date format when mapping

我正在使用 Laravel 和 Elasticsearch。但我无法映射我的 mysql 时间戳,因为默认情况下 ES 仅支持时间戳作为 ISO 8601“2015-02-02T15:30:20”

而且我想映射看起来像“2015-02-15 15:30:22”的时间戳 - 没有 "T"

的 TS

是否可以更改 ES,使其允许时间戳,如“2015-02-15 15:30:22”?

在您的映射中设置 custom date format 以便它接受 MySQL 格式:

curl -XPUT "http://localhost:9200/test/date-format/_mapping" -d'
{
    "date-format" : {
       "properties": {
          "timestamp": {"type": "date","index": "not_analyzed","format" : "yyyy-MM-DD HH:mm:ss"}
        }
    }
}'

然后通过发布消息进行测试:

curl -XPOST "http://localhost:9200/test/date-format" -d'
{
      "timestamp": "2014-10-22 20:03:12"
}'

应该return:

{"_index":"test","_type":"test-date","_id":"AUuD22Ls9cHgxNzY1tfJ","_version":1,"created":true}

Laravel 时间戳通常是 Carbon 实例,因此只需将它们转换为您的 accepted format:

{
  "date-format": {
    "properties": {
      "timestamp": {
        "type": "date",
        "format": "strict_date_optional_time|| epoch_milli"   //default 
      }
    }
  }
}

那么你需要做的就是

$unixEpochMilli = $user->created_at->timestamp * 1000;  //epoch_milli is elastic default
$isoTime = $user->created_at->toIso8601String();   //also a default

请记住,如果您在 Kibana 中查看数据,它默认以浏览器时间显示。只需单击 JSON 表示,您将看到类似 2018-12-19T05:14:21.000Z 的内容,表示存储的纪元。