Emin Mastizada
Emin Mastizada

Reputation: 1405

Multiple ranges in Query for elasticsearch

I would like make query like where price > 555 and price < 5555 and quantity > 33

I have query like:

$query = array(
            'query' => queryFilters($filters),
            'sort' => array($sortOrder[0] => $sortOrder[1], 'updated_at' => 'desc'),
            'from' => ($page - 1) * $pageSize,
            'size' => $pageSize,
        );

Now, lets assume my filters is like:

filter[price_from]=555&filter[price_to]=5555&filter[quantity_from]=33

What should be result of queryFilters($filters) to make it work? I tried filtered query from this doc but result was like or (used array of ranges: 0=>range[...], 1=>range[...], 2=>range[...]) but result was like or query. Any suggestions? I will have query=>constant_score=>filter=>exists=>field[items] and [missing](same structure) in result of queryFilters($filters) also. Using range just for one (price gte, lte) works good, but cant use it for multiple fields (price, quantity).

Upvotes: 0

Views: 1490

Answers (1)

Val
Val

Reputation: 217574

You basically need something like this that uses bool/must with two range filters:

{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": [
            {
              "range": {
                "price": {
                  "gt": 555,
                  "lt": 5555
                }
              }
            },
            {
              "range": {
                "quantity": {
                  "gt": 33
                }
              }
            }
          ]
        }
      }
    }
  }
}

So, your queryFilters function needs to build the above query out of the query string you're getting. I guess it's pretty straightforward from there on.

Upvotes: 3

Related Questions