0

I'm trying to sort my query in elasticsearch where the query will prioritize documents with specific _ids to appear first but it won't filter the entire query based on the _ids it's just prioritizing them.

Here's an example of what I've tried as an attempt:

{"query":{"constant_score":{"filter":{"terms":{"_id":[2,3,4]}},"boost":2}}}

So the above would be included along with other queries however the query just returns the exact matches and not the rest of the results.

Any ideas as to how this can be done so that it just prioritizes the documents with the ids but doesn't filter the entire query?

startupsmith
  • 5,554
  • 10
  • 50
  • 71

2 Answers2

4

Try this (and instead of that match_all() there you can use a query to actually filter the results):

{
  "query": {
    "function_score": {
      "query": {
        "match_all": {}
      },
      "functions": [
        {
          "filter": {
            "terms": {
              "_id": [
                2,
                3,
                4
              ]
            }
          },
          "weight": 2
        }
      ]
    }
  }
}
Andrei Stefan
  • 51,654
  • 6
  • 98
  • 89
  • 1
    Spot on, nice one Andrei ;-) – Val Nov 24 '16 at 06:29
  • Just out of curiosity, is it more performant to use `terms/_id` or simply the `ids` query? – Val Nov 27 '16 at 05:52
  • 1
    The **terms query** uses a boolean query when the scoring is needed. And if there are a lot of ids a TooMantClauses exception can be thrown. If it's a filter, though, those should be equivalent. – Andrei Stefan Nov 27 '16 at 10:08
0

If you need to return in exact order as you need go with

 "sort": [
    {
      "_script": {
        "script": "doc['id'] != null ? sortOrder.indexOf(doc['id'].value.toInteger()) : 0",
        "type": "number",
        "params": {
          "sortOrder": [
            2,3,4
          ]
        },
        "order": "desc"
      }
    },
    "_score"
  ]

P.S. As @Val mentioned wityh _id this will not work, so you would need to store id field as separate.

If you need move documents to top look to function_score

Vova Bilyachat
  • 18,765
  • 4
  • 55
  • 80
  • 1
    In my opinion `doc['_id']` yields nothing unless he also has an `id` field inside the document (like in your other answer), this won't work. – Val Nov 24 '16 at 05:03
  • @Val Originally i have problem with id so i have been using id field – Vova Bilyachat Nov 24 '16 at 05:07