Mary
Mary

Reputation: 1135

In Elasticsearch, why does my query string overmatch?

I'm inserting my data as follows:

PUT my_index2/doc/1
{
  "key": "party",
  "str_val": "THE TWITTER INC"
}

PUT my_index2/doc/2
{
  "key": "party",
  "str_val": "twitter inc"
}

This query:

POST my_index2/_search
{
  "query": {
    "query_string": {
      "default_field": "str_val",
      "query": "*twitter*"
    }
  }
}

correctly returns both results. If I slightly alter my query to:

POST my_index2/_search
{
  "query": {
    "query_string": {
      "default_field": "str_val",
      "query": "*the twitter*"
    }
  }
}

I'm expecting only one result since *the twitter* should only match "THE TWITTER INC" and not "twitter inc". But two results are returned.

Why is my search returning too many matches?

Upvotes: 0

Views: 26

Answers (1)

Polynomial Proton
Polynomial Proton

Reputation: 5135

That is because the default_operator for query_string is OR. You can always use explain:true to know how the result was returned. Like below:

POST my_index2/_search
{
  "query": {
    "query_string": {
      "default_field": "str_val",
      "query": "*the twitter*"
    }
  },
  "explain": true
}

For your case, you need to explicity mention AND to return only documents where both terms match i.e. the AND twitter

 POST my_index2/_search
    {
      "query": {
        "query_string": {
          "default_field": "str_val",
          "query": "*the twitter*",
           "default_operator": "AND"
        }
      }
    }

Upvotes: 2

Related Questions