elasticsearchelasticsearch-6

Elastic search term query not working if used field.keyword


I have below mapping for elastic search

{
   "2021-05-ui":{
      "mappings":{
         "userinfo":{
            "properties":{
               "address":{
                  "type":"text",
                  "fields":{
                     "keyword":{
                        "type":"keyword",
                        "ignore_above":256
                     }
                  }
               },
               "name":{
               "type":"keyword"
            },
            "userId":{
               "type":"keyword"
            }
         }
      }
   }
}

I want to use the term query on userId field like below its doesn't work , but when i remove .keyword from below query its work , i want the query which match exact value for userId field

{
    "query": {
        "bool": {
            "filter": [
                {
                    "term": {
                        "userId.keyword": "test@user.com"
                    }
                }
            ]
        }
    }
}

i want the query with "userId.keyword" only since other environments its has both the text and keyword mapping , could you please suggest which query we can use to get the exact match , i tried using match,match_phrase but didnt help much.


Solution

  • userId field is of keyword type, which means it uses keyword analyzer instead of the standard analyzer. In this case, you will be getting the result only for the exact match

    Since userId is of keyword type and there is no field for userId.keyword, you have to use userId for term query

    {
        "query": {
            "bool": {
                "filter": [
                    {
                        "term": {
                            "userId": "test@user.com"
                        }
                    }
                ]
            }
        }
    }
    

    However if you want to store userId field as of both text and keyword type, then you can update your index mapping as shown below to use multi fields

    PUT /_mapping
    {
      "properties": {
        "userId": {
          "type": "keyword",
          "fields": {
            "raw": {
              "type": "text"
            }
          }
        }
      }
    }
    

    And then reindex the data again. After this, you will be able to query using the "userId" field as of keyword type and "userId.raw" as of text type