Search code examples
elasticsearchelasticsearch-dsl

Elasticsearch Term and Range in Bool Filter


I'm trying to filter my products data by a product type and a price range. I don't want to score my results so they can all be 0 or 1, I just need the result-set.

Why can't I do the following? It seems perfectly logical!

Elasticsearch version: 5.5

GET my_store/products/_search
{
  "query": {
    "constant_score": {
      "filter": {
        "term": {
           "productType": "cooker"
        },
        "range": {
           "price": {
             "gte": 10,
             "lte": 20
            }
         }
       }
     }
   }
}

When I execute this, I get:

"[term] malformed query, expected [END_OBJECT] but found [FIELD_NAME]"

Which presumably means I'm doing something syntactically wrong

  1. Doesn't this seem like a logic structure?
  2. Fine, even if it's wrong, I've got to adapt... So what's the correct syntax?

Solution

  • This should solve your problem. I'm assuming you meant to logically AND the filters. If you meant to OR them, just replace the "must" by "should". A good reference: https://www.elastic.co/guide/en/elasticsearch/guide/current/combining-filters.html

    {
        "query": {
            "constant_score": {
                "filter": {
                    "bool": {
                        "must": [
                            {
                                "term": {
                                    "productType": "cooker"
                                }
                            },
                            {
                                "range": {
                                    "price": {
                                        "gte": 10,
                                        "lte": 20
                                    }
                                }
                            }
                        ]
                    }
                }
            }
        }
    }