How to prioritize the result based on the specified list of ids in Elastic Search query

71 Views Asked by At

To brief:(Elastic Search)

I have set of IDs [12,32,44,32], I need to prioritize the records based on the list of IDs, means I need to bring the record which has the IDs one among the above mentioned list and the rest of the records should be arranged after prioritized 4 record

{
  id:12
  .
  .
},
{
  id:32
  .
  .
},
{
  id:44
  .
  .
},
{
  id:32
  .
  .
},
{
  id:1
  .
  .
},
{
  id:2
  .
  .
},
...

Kindly expecting the answers for query format or the approach to boost the result in query!

1

There are 1 best solutions below

0
Jeevan ebi On BEST ANSWER

We can add the script to the existing filter using SORT without adding boost to the existing query

"sort": [
    {
      "_script": {
        "type": "number",
        "script": {
          "source": "def Ids = [ '12','32','44','22']; def id = doc['id'].value; if (Ids.contains(id)) { return Ids.indexOf(id); } else { return Ids.length + 1; }",
          "lang": "painless"
        }
      }
    }
  ]
  • Inside the script logic, the Ids variable is defined as an array of the IDs you want to prioritize.
  • The script checks if the 'id' field value is one of the specified priority IDs using the contains method. If it is, the script returns the index position of the ID in the Ids array using the indexOf method. If it's not found, the script returns Ids.length + 1. This ensures that non-prioritized IDs are placed at the end of the search results.

This is tested and verified in local.