Represent enum in Elastic Search for sorting

Viewed 356

I have a use case to represent an enum for difficulty level (EASY, MEDIUM, DIFFICULT) in elastic search with support of sorting on this field. If this field is indexed as string the sorting will not work as expected.

One way to support this is to index integer values for each enumeration in ES and map it to string values when sorted results are returned by ES.

Are there other alternatives such that ES itself takes care of sorting in the enumeration order while this field is indexed as string? Can I specify custom sort function for a field? function_score is an option, but given that I have to sort based on enum ordering is there better way than defining custom function_score?

In my use case there are multiple such enumeration defining scale across dimensions like difficulty, height (low, medium, high), grades (good, average, poor), etc. Both the above solution requires custom work as a new dimension is introduced. Can either of the above approach be generalzied?

1 Answers

You can check the answer to the same question here. You will need to use script_score like below:

GET /my-index-2/_search
{
  "query": {
    "script_score": {
      "query": {
        "match_all":{}
      },
      "script": {
        "source": "if (doc['field name'].value == 'EASY'){2} else if(doc['field name'].value == 'MEDIUM') {1} else if(doc['field name'].value == 'DIFFICULT') {0}"
      }
    }
  }
}
Related