How to force the order of a `terms` query?

Viewed 308

I have a simple terms query with a list of IDs defined. My goal is to get results back in the same order as it was defined in the input array. How to achieve that?

{
    query: {
        terms: {
            _id: ["12", "34", "6", "22"]
        }
    }
}
1 Answers

You can use Script based sorting for same. you can provide sort order and based on it, script will order your response.

POST index/_search
{
  "query": {
    "terms": {
      "id": ["12", "34", "6", "22"]
    }
  },
  "sort": {
    "_script": {
      "type": "number",
      "script": {
        "inline": "params.sortOrder.indexOf(doc['id'].value)",
        "params": {
          "sortOrder": ["12", "34", "6", "22"]
        }
      },
      "order": "asc"
    }
  }
}
Related