Elastic Search wildcard search with spaces Elastic Search wildcard search with spaces elasticsearch elasticsearch

Elastic Search wildcard search with spaces


What is the mapping you have used for your field name? If you have not defined any mapping or you have just defined the type as string (without any analyzer) then the field will be analyzed using the standard analyzer. This will create tokens as "hello" and "world" separately. This means wildcard query will work for something like *ell* or *wor* but not with spaces.

You have to change your mapping to have the field "name" as not_analyzed then wildcard searches with space will work.

A word of caution: Wildcard searches are heavy. If you want to do partial matching search (equivalent of %like%) You can use ngram token filter in your analyzer and do term search. It will take care of matching partial string and have better performance too.


You need to use

match_phrase: {"field_name": "some phrase with spaces"}

As mentioned in the official docs,

To perform a phrase search rather than matching individual terms, you use match_phrase instead of match


The "string" type is legacy and with index "not_analyzed" it is mapped to the type "keyword" which is not divided into substrings. I had problems with queries including spaces before though and solved it by splitting the query in substrings at the blank spaces and making a combined query, adding a wildcard-object for every substring, using "bool" and "must":

{  "query": {    "bool": {      "must": [        {          "wildcard": {            "name": "*hello*"          }        },        {          "wildcard": {            "name": "*world*"          }        }      ]    }  }}

This method has the small drawback that "hell world!" and other unexpected strings end up in your result. You could solve that by changing "wildcard" to "match" for all but the last substring.

You should try to solve it by first changing the type of the field:

PUT your_index{  "mappings": {    "your_index": {      "properties": {        "your_field1": {           "type": "keyword"            },        "your_field2": {            "type": "string",            "index": "not_analyzed"            }         }      }    }  }}