akhilsp
akhilsp

Reputation: 1103

Elasticsearch 5 - case insensitive exact matching in a text/keyword field

I have an entity_name field in my document in ES, which is a text/keyword field whose mapping is as follows:

{
  "my_index": {
    "mappings": {
      "my_type": {
        "properties": {
          "entity_name": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }
        }
      }
    }
  }
}

What I am trying to achieve is to build a query to get documents containing 'ABC' in their entity_name field (like 'ABC Company', 'company abc'), but should exclude those having exactly 'ABC' case-insensitively (like 'ABC', 'abc', 'Abc').

I've tried queries like:

{
  "query": {
    "bool": {
      "must": [
        {
          "match_phrase": {
          "entity_name": "ABC"
          }
        }
      ],
      "must_not": [
        {
          "term": {
          "entity_name.keyword": "ABC"
          }
        }
      ]
    }
  }
}

But it does not handle the case-insensitivity problem.

Any help would be greatly appreciated. Thanks in advance :)

Upvotes: 2

Views: 2107

Answers (1)

Lucas Hendren
Lucas Hendren

Reputation: 2826

Try adding a tokenizer to it to help filter your search

{
  "my_index": {
    "settings": {
      "analysis": {
         "analyzer": {
            "case_insensitive": {
               "tokenizer": "keyword",
               "filter": [
                  "lowercase"
               ]
            }
         }
      }
   },
    "mappings": {
      "my_type": {
        "properties": {
          "entity_name": {
            "type": "text",
           "analyzer": "case_insensitive",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }
        }
      }
    }
  }
}

https://www.elastic.co/guide/en/elasticsearch/reference/5.4/analysis-tokenizers.html

Upvotes: 3

Related Questions