Elasticsearch and case sensitive term queries

Florian Hirsch
1 min readFeb 23, 2015

--

I just stumbled upon a problem which seemed quite weird at first glance. All I wanted to do is filtering for some enum values. Let’s say we want to index a document like this:

curl -XPOST "http://localhost:9200/index-1/user/" -d'
{
"name" : "John Doe",
"roles" : [ "LOGIN" ]
}'

Filtering for all users with the role LOGIN should be as easy as this:

curl -XPOST "http://localhost:9200/index-1/user/_search" -d'
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"term": {
"roles": "LOGIN"
}
}
}
}
}'

But this query returns 0 hits. Ironically we will find John if we are searching with the wrong case:

curl -XPOST "http://localhost:9200/index-1/user/_search" -d'
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"term": {
"roles": "login"
}
}
}
}
}'

Why is that? The documentation for the term query stats:

Matches documents that have fields that contain a term (not analyzed).

So the search term will not be analyzed but on indexing Elasticsearch will analyze the field lowercase unless you define a custom mapping.

So if you want to use a term query — analyze the term on your own before querying. Or just lowercase the term in this case.

--

--