Elastic Search

Wildcard Query Elasticsearch

A wildcard refers to a special placeholder character interpreted and replaced with various iterations based on its location. Using wildcards is common when performing searches, especially where the target search is not accurately known.

In Elasticsearch, there are two ways to search for items without knowing the exact match. The first is to use fuzziness (check our tutorial on the topic), and the other is to use wildcard search.

This tutorial will teach you how to use wildcard search queries to locate items without knowing the exact match.

Basic Usage

To illustrate how to use the Elasticserch wildcard query, we will use the kibana-sample-eCommerce data index.

In the index, we have customers’ information. Suppose we want to get the results where the first name of the customer matches j*y.

We can perform a query as shown:

GET /kibana_sample_data_ecommerce/_search?pretty
{
 "query": {
   "wildcard": {
     "customer_first_name": {
       "value": "j*n",
       "boost": 2
     }
   }
 }
}

If we execute the request on the index, we should get the documents where the customer_first_name starts with a j and ends with an n.

A sample screenshot of the response is below:

Suppose we know the exact number of characters in the name. For example, we are not sure if it’s Jim or Jimmy; we can use the ? character as:

GET /kibana_sample_data_ecommerce/_search?pretty

{
 "query": {
   "wildcard": {
     "customer_first_name": {
       "value": "j?m*",
       "boost": 2
     }
   }
 }
}

The example query should return the documents where the first name starts with a j, includes one single character, followed by a letter m and other characters.

Below is an example response:

Wildcard Query Parameters

You can specify various parameters to modify how the wildcard query functions. Such parameters include:

  1. Field – The field to search for a matching pattern. This parameter is not optional. In our example above, the field is set to customer_first_name.
  2. Value – This defines the wildcard pattern to search. A single question mark indicates a single character, while a * means zero or more characters, including an empty character. The value parameter is not optional.
  3. Boost – The boost parameter increases or decreases the score weight of the search query. This is an optional parameter and is set to 1.0 by default. To increase score weight, set a value higher than 1.0 and a value less than 1.0 to decrease the score.

Conclusion

In this article, we explained how to use the wildcard search queries in Elasticsearch. Consider the documentation or our topics on Elasticsearch to learn more.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list