34

Does Elasticsearch allow us to query documents case-insensitive? Or should I save them as case-insensitive before querying? Or is there some setting that I should set for the whole index to make it case-insensitive?

Can you clarify this moment please?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Skrudox
  • 839
  • 4
  • 9
  • 14

1 Answers1

22

By Default, the fields are case-insensitive because of the mapping elastic applied.

Try below:

PUT myindex/doc/1
{
  "name":"TEST"
}

GET myindex/_mapping

It should return :

{
  "myindex": {
    "mappings": {
      "doc": {
        "properties": {
          "name": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }          
        }
      }
    }
  }
}

Now if you query with below, it will return a match (notice the mapping[text and keyword]):

POST myindex/_search
{
  "query": {
    "match": {
      "name2": "test"
    }
  }
}

Now, if you explicitly specify to index the field as keyword, then it will be case-sensitive search. Try below and see; it will not return any results.

PUT myindex/_mapping/doc
{
  "properties": {
    "name2": {
      "type": "keyword"
    }
  }
}

PUT myindex/doc/1
{
  "name2":"TEST"
}


POST myindex/_search
{
  "query": {
    "match": {
      "name2": "test"
    }
  }
}

TLDR; Use default mapping or text type- if you specify the field to index only keyword type, it will be case-sensitive.

Polynomial Proton
  • 5,020
  • 20
  • 37
  • 19
    This works, because a field containing `"test"` will be automatically mapped as `text`, which gets processed by the standard analyzer. That analyzer uses the `lowercase` token filter, so it will index that field as lowercase, and will convert query terms to lowercase at query time. You'll learn all about analyzers and token filters if you get to the point where you need to create a custom analyzer (e.g. for language-specific analyzers, using synonyms, etc.). – dmbaughman Jun 27 '18 at 22:40
  • 1
    answer is misleading without the above comment. – aandis May 21 '21 at 04:41
  • I didn't explicitly mention the mapping for few string(text) fields. So, ElasticSearch took care of that. ` "name" : { "type" : "text", "fields" : { "keyword" : {"type" : "keyword","ignore_above" : 256}}}` But, when I am trying to search for this specific name field (using query_string type of query ) . I am not getting results for case insensitive search. Where as, I am getting results when I give capital letters. ES version - AWS ES - 7.7 – Batman May 28 '21 at 07:20
  • 3
    This doesn't become case insensitive. What if I want to search TeSt(Entered by user)? this will not support this. One thing what we can do, We can decapitalising the input from user and make search – Manonandan S K Jan 25 '22 at 07:48