代码之家  ›  专栏  ›  技术社区  ›  funseiki

将日期插入为epoch\u seconds,输出为格式化日期

  •  0
  • funseiki  · 技术社区  · 7 年前

    我有一组时间戳,格式为从纪元开始的秒。我想插入ElasticSearch作为 epoch_seconds 但是,当查询希望将输出视为一个漂亮的日期时,例如:。 strict_date_optional_time

    我下面的映射保留了输入的格式-有没有办法通过 mapping api?

    当前映射:

    PUT example
    {
      "mappings": {
        "time": {
          "properties": {
            "time_stamp": {
              "type": "date",
              "format": "strict_date_optional_time||epoch_second"
            }
          }
        }
      }
    }
    

    示例文档

    POST example/time
    {
      "time_stamp": "2018-03-18T00:00:00.000Z"
    }
    
    POST example/time
    {
      "time_stamp": "1521389162" // Would like this to output as: 2018-03-18T16:05:50.000Z
    }
    

    获取示例/\u搜索输出:

    {
        "total": 2,
        "max_score": 1,
        "hits": [
          {
            "_source": {
              "time_stamp": "1521389162", // Stayed as epoch_second
            }
          },
          {
            "_source": {
              "time_stamp": "2018-03-18T00:00:00.000Z"
            }
          }
        ]
      }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Sjon    7 年前

    Elasticsearch区分 _source 而所谓的 存储字段 . 第一个应该代表您的输入。

    如果实际使用存储字段(通过指定 store=true 然后指定 multiple date formats 这很简单:(强调我的)

    可以通过使用| |作为分隔符分隔格式来指定多种格式。将依次尝试每种格式,直到找到匹配的格式。 第一种格式将用于将历元值之后的毫秒转换回字符串。

    我已经用elasticsearch 5.6.4测试过了,效果很好:

    PUT /test -d '{ "mappings": {"doc": { "properties": {"post_date": {
        "type":"date",
        "format":"basic_date_time||epoch_millis",
        "store":true
    } } } } }'
    
    PUT /test/doc/2 -d '{                                                                                                                            
        "user" : "test1",
        "post_date" : "20150101T121030.000+01:00"
    }'
    
    PUT /test/doc/1 -d '{                                                                                                                            
        "user" : "test2",
        "post_date" : 1525167490500
    }'
    

    请注意,使用时,两种不同的输入格式将导致相同的格式 GET /test/_search?stored_fields=post_date&pretty=1

    {
        "hits" : [
          {
            "_index" : "test",
            "_type" : "doc",
            "_id" : "2",
            "_score" : 1.0,
            "fields" : {
              "post_date" : [
                "20150101T111030.000Z"
              ]
            }
          },
          {
            "_index" : "test",
            "_type" : "doc",
            "_id" : "1",
            "_score" : 1.0,
            "fields" : {
              "post_date" : [
                "20180501T093810.500Z"
              ]
            }
          }
        ]
    }
    

    如果要更改输入(在 _来源: )你没那么幸运 mapping-transform 功能已删除:

    这在2.0.0中被弃用,因为它使调试变得非常困难。到目前为止,除了在客户端应用程序中转换文档之外,还没有其他功能可以替代它使用。

    如果您对格式化输出感兴趣,而不是更改存储的数据,请查看 this answer to Format date in elasticsearch query (during retrieval)