ElasticSeach - sort by date

I have an elastic search index that I cannot configure each field with a display, so the dates go as strings ...

Does anyone know how I will sort by this string date?

I looked at _script

{ "query" : { .... }, "sort" : { "_script" : { "script" : "doc['field_name'].value", "type" : "string", "order" : "asc" } } } 

But this fails because its field analyzed ...

Any suggestions would be great!

thanks

+4
source share
1 answer

If the date format is known, you can add this format to dynamic_date_formats (Check this link). When you index a new string field, it will be converted to a date type, which can be sorted in the usual way.

Example:

Create an index without properties:

 curl -XPUT http://localhost:9200/dates -d ' { "dates" : { "dynamic_date_formats" : ["yyyy-MM-dd", "dd-MM-yyyy"], "properties" : { } } }' 

Index 2 docs:

 curl -XPUT 'http://localhost:9200/dates/dates/1' -d ' { "arbitraryDate": "2013-01-01" }' curl -XPUT 'http://localhost:9200/dates/dates/2' -d ' { "arbitraryDate": "2012-01-01" }' 

If you check the mapping, you will see that the field is not a string:

 curl -XGET 'http://localhost:9200/dates/_mapping' 

result:

 { "dates": { "dates": { "properties": { "arbitraryDate": { "type": "date", "format": "dateOptionalTime" } } } } } 

Now you can easily sort:

 curl -XGET 'http://localhost:9200/dates/_search' -d ' { "query": { "match_all": {} }, "sort": [ { "arbitraryDate": { "order": "asc" } } ] }' 
+7
source

Source: https://habr.com/ru/post/1498622/


All Articles