elasticsearchelasticsearch-queryterm-query

Elastic search query not returning results


I have an Elastic Search query that is not returning data. Here are 2 examples of the query - the first one works and returns a few records but the second one returns nothing - what am I missing?

Example 1 works:

curl -X GET "localhost:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "match": {
      "data.case.field1": "ABC123"
    }
  }
}
'

Example 2 not working:

curl -X GET "localhost:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "bool": {
      "must": {
        "term" : { "data.case.field1" : "ABC123" }
      }
    }
  }
}
'

Solution

  • this is happening due to the difference between match and term queries, match queries are analyzed, which means it applied the same analyzer on the search term, which is used on field at index time, while term queries are not analyzed, and used for exact searches, and search term in term queries doesn't go through the analysis process.

    Official doc of term query

    Returns documents that contain an exact term in a provided field.

    Official doc of match query

    Returns documents that match a provided text, number, date or boolean value. The provided text is analyzed before matching.

    If you are using text field for data.case.field1 without any explicit analyzer than the default analyzer(standard) for the text field would be applied, which lowercase the text and store the resultant token.

    For your text, a standard analyzer would produce the below token, please refer Analyze API for more details.

    {
        "text" : "ABC123",
        "analyzer" : "standard"
    }
    

    And generated token

    {
        "tokens": [
            {
                "token": "abc123",
                "start_offset": 0,
                "end_offset": 6,
                "type": "<ALPHANUM>",
                "position": 0
            }
        ]
    }
    

    Now, when you use term query as a search term will not be analyzed and used as it is, which is in captical char(ABC123) it doesn't match the tokens in the index, hence doesn't return result.

    PS: refer my this SO answer for more details on term and match queries.