Combination of faceted and full-text query

Task:
I am using full-text search and faceted search in a single query. However, I encountered an issue: if the search by query (e.g., brand or product name) yields no results, it returns all products that match the filters. My goal is to ignore the filters if a query is provided and there are no results for it.

Example 1:

  • Query: 82jsisiwjaon (non-existent query)
  • Filter: gender: male
  • Current result (undesired): [items, …] (all products matching the gender: male filter, ignoring the fact that the query yielded no results).
  • Expected result: [] (empty result, as the query yielded no matches, and filters should not be applied).

Example 2:

  • Query: nike (existing query)
  • Filter: gender: male
  • Expected result: [items, …] (products that match both the query and the filter).

Reproduction Script:
Here is an example query I am using:

POST /catalog_products/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "should": [
              {
                "multi_match": {
                  "query": "nike",  // Replace with "82jsisiwjaon" for the first example
                  "fields": ["title", "slug"],
                  "analyzer": "icu_analyzer",
                  "fuzziness": "AUTO",
                  "boost": 15
                }
              }
            ],
            "minimum_should_match": 1
          }
        }
      ],
      "filter": [
        {
          "term": {
            "gender": "male"
          }
        }
      ]
    }
  },
  "size": 10,
  "from": 0
}

Problem:
If the query (e.g., 82jsisiwjaon ) yields no results, the filter gender: male is still applied, and all products matching the filter are returned. How can I ensure that filters are ignored if the query yields no results?

Welcome!

Could you provide a full recreation script as described in About the Elasticsearch category. It will help to better understand what you are doing. Please, try to keep the example as simple as possible.

A full reproduction script is something anyone can copy and paste in Kibana dev console, click on the run button to reproduce your use case. It will help readers to understand, reproduce and if needed fix your problem. It will also most likely help to get a faster answer.

Have a look at the Elastic Stack and Solutions Help · Forums and Slack | Elastic page. It contains also lot of useful information on how to ask for help.

1 Like