Return docs with specific value to the top and order the rest by rand


(Oscar Sanchez Sanchez) #1

Hi there, I would like ES to return documents that have a field is_sticky with value true to the top on a match all query. The rest of the results that have a false value should be ordered by rand.

Currently, I got the is_sticky docs return to the top by sending this request:

{
    "query": {
        "function_score": {
          "query": { "match_all": {} },
          "functions": [
              {
                  "filter": { "match": { "is_sticky": "true" } },
                  "weight": 2
              }
          ]
        }
    }
}

The rest of the docs with value is_sticky: false are not returned by rand (probably because i did not used random_score), but I'm not really sure. How could I accomplish this?

Thanks in advance, and hope you have a great day.


(Mayya Sharipova) #2

Hi there! This query should help you with your task:

{
  "query": {
    "function_score": {
      "query": { 
        "match_all": {}
      },
      "functions": [
        {
          "filter": { "match": { "is_sticky": "true" } },
          "weight": 2
        },
        {
          "random_score" : {}
        }
      ],
      "boost_mode" : "replace",
      "score_mode" : "sum"
    }
  }
}

(Oscar Sanchez Sanchez) #3

Hi mayya,

Appreciate your reply. I'll test this out and see how it goes.

Thank you very much!