Search code examples
elasticsearchelasticsearch-dsl

How to use term query when the keyword type is text in elasticsearch


Hi i have created an mapping in elasticsearch for claimnumber field when i use to search the term using term query it's working fine for text full of numbers but not working for the text combination of alphabet and numbers for example working for "123456" not working for "CL123456"

mapping below

{
  "duckcreek" : {
    "mappings" : {
      "properties" : {
        "@timestamp" : {
          "type" : "date"
        },
        "@version" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
          "claimnumber" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
          "id" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "policynumber" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "url" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
    }
  }
}

working for numbers

GET duckcreek/_search
{
  "query": {
    "term": {
      "claimnumber": {
        "value": "99520"
      }
    }
  }
}

not working text with numbers

GET duckcreek/_search
{
  "query": {
    "term": {
      "claimnumber": {
        "value": "CL123456"
      }
    }
  }
}

Kindly suggest a solution to resolve this?


Solution

  • While performing an analysis on the text string using Analyze API

    GET /_analyze
    
    {
      "analyzer" : "standard",
      "text" : "CL123456"
    }
    

    The tokens generated are:

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

    Search Query

    {
      "query": {
        "term": {
          "title.keyword": {     <-- note this
            "value": "CL123456"
          }
        }
      }
    }
    

    Search Result

    "hits": [
          {
            "_index": "matchprase1",
            "_type": "_doc",
            "_id": "2",
            "_score": 0.6931471,
            "_source": {
              "title": "CL123456"
            }
          }
        ]