0
0
Elasticsearchquery~5 mins

Wildcard and prefix queries in Elasticsearch

Choose your learning style9 modes available
Introduction

Wildcard and prefix queries help you find words that match a pattern or start with certain letters. They make searching flexible and easy.

You want to find all documents with words starting with 'play', like 'play', 'player', or 'playing'.
You want to search for words that match a pattern with unknown letters, like 'c?t' to find 'cat', 'cut', or 'cot'.
You want to find documents with words ending or containing certain letters using wildcards.
You want to quickly search for terms without typing the full word.
You want to support user searches that may have typos or partial words.
Syntax
Elasticsearch
{
  "query": {
    "wildcard": {
      "field_name": {
        "value": "pattern"
      }
    }
  }
}

{
  "query": {
    "prefix": {
      "field_name": "prefix_value"
    }
  }
}

Use ? for a single unknown character and * for any number of unknown characters in wildcard queries.

Prefix queries only need the beginning letters of the word to match.

Examples
This finds names like 'john', 'joan', or 'johnson' because ? matches one letter and * matches any letters after.
Elasticsearch
{
  "query": {
    "wildcard": {
      "name": {
        "value": "jo?n*"
      }
    }
  }
}
This finds cities starting with 'new', like 'newyork' or 'newark'.
Elasticsearch
{
  "query": {
    "prefix": {
      "city": "new"
    }
  }
}
Sample Program

This query searches for products with names like 'camera', 'camara', or 'camira' because ? matches one letter and * matches any letters after.

Elasticsearch
{
  "query": {
    "wildcard": {
      "product": {
        "value": "cam?ra*"
      }
    }
  }
}
OutputSuccess
Important Notes

Wildcard queries can be slower because they check many possibilities.

Prefix queries are faster and good for autocomplete features.

Use lowercase for terms if your index is case-sensitive.

Summary

Wildcard queries let you search with ? and * to match patterns.

Prefix queries find words starting with a given string.

Use these queries to make flexible and user-friendly searches.