Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ElasticSeach - Sorting on dates

I have an elastic search index which I cannot setup every field with a mapping so dates are going in as strings...

Does anyone know how I would go about sorting on that string date?

I have looked at _script

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

But this fails because its an analysed field...

Any suggestions would be great!

Thanks

like image 909
user1076082 Avatar asked Aug 23 '13 14:08

user1076082


People also ask

How do I sort in Elasticsearch query?

Sort mode optioneditPick the highest value. Use the sum of all values as sort value. Only applicable for number based array fields. Use the average of all values as sort value.

How does Elasticsearch sort work?

In order to sort by relevance, we need to represent relevance as a value. In Elasticsearch, the relevance score is represented by the floating-point number returned in the search results as the _score, so the default sort order is _score descending. In the previous example, we searched for movies from 1962.


1 Answers

If the format of the date is known, you can add that format to the dynamic_date_formats (Check out this link) setting. When you index a new string field it will be converted to the date type which can be sorted in the normal 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 documents:

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 sort easily:

curl -XGET 'http://localhost:9200/dates/_search' -d '
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "arbitraryDate": {
        "order": "asc"
      }
    }
  ]
}'
like image 185
moliware Avatar answered Dec 01 '22 12:12

moliware