jdkealy
jdkealy

Reputation: 4907

sorting with a list in elasticsearch

I have a query where I ask elasticsearch for a list of records based on a list of ids. e.g.

match: ids: [1,2,3]

Would it be possible to tell elasticsearch to return the elements to me in that order? My list of ids will be in the hundreds and I'm paginating the elements in chunks of 25.

It would be great if I could so something like

{match: ids [1,2,3] sort: ids [3,1,2}

Any suggestions would be very helpful. Thanks!

Upvotes: 1

Views: 1149

Answers (1)

Henrik
Henrik

Reputation: 633

If possible use Multi Get:

POST /orderbyids/_mget
{
    "ids" : [12, 80, 44, 50]
}

An alternative is to use dynamic scripting:

POST /orderbyids/_search
{
  "query": {
    "function_score": {
      "query": {
        "ids": {
          "values": [
            50,
            80,
            44,
            12
          ]
        }
      },
      "script_score": {
        "params": {
          "ids": [
              12,
              80,
              44,
              50
          ]
        },
        "script": "return -ids.indexOf(doc['id'].value.intValue());"
      }
    }
  }
}

The functionality have been discussed in a closed issue.

Upvotes: 3

Related Questions