Skip to content Skip to sidebar Skip to footer

Sort Elasticsearch Results By A Custom Compare Function On Field

If I want to fetch Driver data from elastic sorted on rating where rating could be ['good', 'ok', 'bad'], how to write the query which can help me get data in sorted order consider

Solution 1:

For changing score value based on a field in your index you can use script score query, your query should look like below example:

GET /my-index-2/_search
{
  "query": {
    "script_score": {
      "query": {
        "match_all":{}
      },
      "script": {
        "source": "if (doc['rating.keyword'].value == 'good'){2} else if(doc['rating.keyword'].value == 'ok') {1} else if(doc['rating.keyword'].value == 'bad') {0}"
      }
    }
  }
}

For more information about script score query you can check Elastic official documentation here.

Post a Comment for "Sort Elasticsearch Results By A Custom Compare Function On Field"