Search code examples
elasticsearchelasticsearch-7

Elasticsearch query on zip_code failed


I have a strange behavior on elasticsearch that I cant explain.

When I do :

POST /ad_search/_search
{
  "query": {
    "match": {
      "city_code": "2A247"
    }
  }
}

I have multiple result. But when I do (This code is generated by a librairies) :

POST /ad_search/_search
{
  "from":0,
  "query": {
    "bool": {
      "must":[
        {"term":{"city_code":"2A247"}}
      ]
    }
  }
}

I have no result.

When I search on all other zip_code with only numbers like 71459. The both query are working well and give me the same result.

I was thinking of a mapping problems but it seems ok :

GET /ad_search/_mapping
{
  "ad_search" : {
    "mappings" : {
      "properties" : {
        "city_code" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
    }
  }
}

Someone have any ideas to unlock me ?

Thank you


Solution

  • It's because city_code is of type text and thus analyzed, hence what is being indexed is 2a247 (lowercase).

    So you can either query city_code.keyword with a term query, which does an exact match

    POST /ad_search/_search
    {
      "from":0,
      "query": {
        "bool": {
          "must":[
            {"term":{"city_code.keyword":"2A247"}}
          ]
        }
      }
    }
    

    Or with a match query on the city_code field:

    POST /ad_search/_search
    {
      "from":0,
      "query": {
        "bool": {
          "must":[
            {"match":{"city_code":"2A247"}}
          ]
        }
      }
    }