How to get result that contains every word in the query

Hi there, I would like have elasticsearch return only the docs that contain every word in the query. For example, if the user queries "wooden table", docs with "...wooden table ....." and "table .... with wooden...." will be returned but not docs that only contain "wooden" or "table". The number of words in the query is undefined so having multiple AND in query might not be ideal. I read about min_score https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html#request-body-search-min-score, but I am not sure how min_score is defined or works. It does not seem to be cosine similarity score, as still get result if min_score is set over 1.

Also, how can I return docs that contains the exact ordered words in the query. If "wooden table" is queries, how can I return docs that only contains "...wooden table...." , but not "wooden....table..." or "table wooden" or anything else.

Thanks in advance.

I'm not sure why AND would not be the solution here. You can pass in the AND operator to a match query and it will only return documents that match all your search terms:

GET my_index/_search
{
  "query": {
    "match": {
      "my_field": {
        "query": "wooden table",
        "operator": "and"
      }
    }
  }
}

If you only need a certain number of search terms to match, you can use the minimum_should_match parameter. This parameter accepts a specific number, or a percentage. For example:

GET my_index/_search
{
  "query": {
    "match": {
      "my_field": {
        "query": "beautiful wooden table",
        "minimum_should_match": "80%"
      }
    }
  }
}

To match the exact phrase "wooden table" you can use the match_phrase query:

GET my_index/_search
{
  "query": {
    "match_phrase": {
      "my_field": {
        "query": "wooden table"
      }
    }
  }
}
1 Like

Thank you so much!

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.