पाठ 11 / 25

The bool Query and Term-Level Queries

Combine scoring with filtering.

must, filter, should, must_not

A bool query combines clauses. must clauses must match and contribute to the score. filter clauses must match but run in filter context: no scoring, and frequently used filters can be cached, so put every yes/no condition (status, price range, tenant id, dates) there. should clauses add to the score when they match; if a bool has no must or filter, at least one should must match (adjust with minimum_should_match). must_not excludes documents, also without scoring. Term-level queries (term, terms, range, exists, prefix, ids) do not analyse their input, so use them on keyword, numeric, date and boolean fields.

A search box plus filters

Kibana Dev Tools console syntax; send the same requests with curl or a client library.

GET /products/_search
{
  "query": {
    "bool": {
      "must": [
        { "multi_match": { "query": "rain jacket", "fields": [ "name^3", "description" ] } }
      ],
      "filter": [
        { "term":  { "in_stock": true } },
        { "terms": { "brand": [ "Northpeak", "Fjellgear" ] } },
        { "range": { "price": { "gte": 50, "lte": 200 } } }
      ],
      "should": [
        { "term": { "tags": "bestseller" } }
      ],
      "must_not": [
        { "term": { "status": "discontinued" } }
      ]
    }
  }
}

Filters do not change the ranking

Moving a condition from must to filter keeps the same matching documents but stops it influencing scores, which is what you want for exact constraints and is cheaper.

त्वरित जाँच: Where should an exact condition like tenant_id = 42 go in a bool query?

  • In a function_score weight
  • In must, using a match query
  • In should, so it can be skipped
  • In filter, using a term query
Answer

In filter, using a term query — Filter context is exact, unscored and cacheable.