Skip to content Skip to sidebar Skip to footer

Elastic - Sorting Value With Priority

So, i have 1 field, we can call it timeInt. the type value is integer. The value is counted from 0. And i want to sort it with priority condition. 0 / 1 will be placed on the top t

Solution 1:

You can apply boost to the values 0 and 1 in a should and then modify your sort query by including _score field as shown below.

Also looking at your expected result, the sorting order for timeInt would be desc and not asc.

POST <your_index_name>/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match_all": {}
        },
        {
          "match": {
            "timeInt": {
              "query": 0,
              "boost": 3
            }
          }
        },
        {
          "match": {
            "timeInt": {
              "query": 1,
              "boost": 2
            }
          }
        }
      ]
    }
  },
  "sort": [
    { "_score": "desc"},
    {
      "timeInt": {
        "order": "desc"
      }
    }
  ]
}

Below is how your results would appear:

{"took":3,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":5,"relation":"eq"},"max_score":null,"hits":[{"_index":"myintindex","_type":"_doc","_id":"2","_score":4.0,"_source":{"timeInt":0},"sort":[4.0,0]},{"_index":"myintindex","_type":"_doc","_id":"1","_score":3.0,"_source":{"timeInt":1},"sort":[3.0,1]},{"_index":"myintindex","_type":"_doc","_id":"3","_score":1.0,"_source":{"timeInt":99},"sort":[1.0,99]},{"_index":"myintindex","_type":"_doc","_id":"4","_score":1.0,"_source":{"timeInt":98},"sort":[1.0,98]},{"_index":"myintindex","_type":"_doc","_id":"5","_score":1.0,"_source":{"timeInt":97},"sort":[1.0,97]}]}}

Note: All the other documents have the _score of 1, because of the match_all query.

Let me know if this helps!

Post a Comment for "Elastic - Sorting Value With Priority"