Joey Yi Zhao
Joey Yi Zhao

Reputation: 42556

How to user long value as a `Date` type in Elasticsearch?

I am using Elasticsearch 7.10.1. My document has a field timestamp whose value is long, e.g. 1624841520000. I tried to change it to use Date type but failed:

PUT myindex/_mapping
{
      "properties": {
        "timestamp": {
          "type": "date" 
        }
      }
    
}

The error response is:

{
  "error" : {
    "root_cause" : [
      {
        "type" : "illegal_argument_exception",
        "reason" : "mapper [timestamp] cannot be changed from type [long] to [date]"
      }
    ],
    "type" : "illegal_argument_exception",
    "reason" : "mapper [timestamp] cannot be changed from type [long] to [date]"
  },
  "status" : 400
}

How can I use this field as date?

Upvotes: 1

Views: 3002

Answers (2)

Han Ye
Han Ye

Reputation: 158

Create or update like this should solve your problem:

PUT myindex/_doc/<the_doc_id_of_your_data>
{
   "data_field": "data_value",
   "timestamp": 1626336886075
}

Where <the_doc_id_of_your_data> should be replaced by the doc_id you would specify.

Note that there is a _doc lie between your index name and the doc_id.

Date field type doc says date type accepts milliseconds-since-the-epoch value as input. The reason you still got that error might be that, according to the doc of index API, you must use one of the following form of path parameter:

  • PUT /<target>/_doc/<_id>
  • PUT /<target>/_create/<_id>
  • POST /<target>/_create/<_id>

And you might just missed the path parameter.

Upvotes: 0

leandrojmp
leandrojmp

Reputation: 7473

You can't change the mapping type, you will need to delete the index and create the mapping before indexing the document.

Later versions, starting with 7.11 using the Elastic license, have the option to create runtime fields, that allows to change the mapping at query time, but this is not possible with version 7.10.

Upvotes: 2

Related Questions