简体   繁体   中英

how do i get `sort` and `bool => should` query to work in tandem?

I have the following query for fetching all products, what i'am trying to achieve is keep the out of stock products IE products with stock_sum = 0 at the bottom :-

{
  "sort": [
    {
      "updated_at": {
        "order": "desc"
      }
    }
  ],
  "size": 10,
  "from": 0,
  "query": {
    "bool": {
      "should": [
        {
          "range": {
            "stock_sum": {
              "gte": 1,
              "boost": 5
            }
          }
        }
      ]
    }
  }
}

But with the above query sort seems to completely override should , which is how its suppose to behave i guess, a couple of things that i tried are changing the should to must in this case the out of stock products, are left out completely (thats not what i want, i still want the out of stock products at the bottom).

Another approach is remove sort , and then the should query seems to have an effect , but again i need the sort. so my question is how do i get sort and bool => should query to work in tandem ? IE sort by updated_at but also keep the stock_sum = 0 at the bottom ?

Using match_all and constant_score query in the same should clause and sorting first by _score by asc , then by updated_at by desc should work for your example. Here is an example query:

{
  "sort": [
    {
      "_score": {
        "order": "asc"
      }
    },
    {
      "updated_at": {
        "order": "desc"
      }
    }
  ]
  "query": {
    "bool": {
      "should": [
        {
          "match_all": {}
        },
        {
          "constant_score": {
             "filter": {
              "term": {
                "stock_sum": 0
              }
            },
            "boost": 10
          }
        }
      ]
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM