A search box is one of the most frequently used features in an application. Whether users are searching for products, articles, customers, locations, or technical documentation, they usually expect suggestions to appear while they type.
For example, when a customer enters "lap" in an online shopping application, the search box might suggest "Laptop", "Laptop Accessories", and "Laptop Stand". The user can select a suggestion instead of typing the complete search term.
Building this feature with a regular database query is possible, but it can become expensive when the search index contains millions of records. Running wildcard queries or repeatedly searching large text fields after every keystroke may introduce unnecessary database work and inconsistent response times.
Elasticsearch provides a specialized feature called the Completion Suggester for this scenario. It uses an optimized in-memory data structure to return matching suggestions quickly as users type. Developers can also configure suggestion weights, fuzzy matching, duplicate filtering, and contexts to control which suggestions appear.
This article explains how to build an autocomplete feature using Elasticsearch completion fields, from mapping and indexing suggestions to querying, ranking, and integrating the feature into an application.
Understanding the Elasticsearch Completion Suggester
The Completion Suggester is designed for search-as-you-type functionality. Its primary purpose is to help users navigate toward relevant search results before they finish entering a query.
It is different from a regular full-text search operation.
A full-text search query analyzes the entered text and searches indexed documents for matching terms. A completion query uses a specialized structure to retrieve suggestions based on the beginning of an indexed input.
For example, consider an application that contains these products:
Laptop
Laptop Stand
Laptop Backpack
Wireless Keyboard
Wireless Mouse
Monitor
When a user enters "lap", the completion suggester can return the first three matching suggestions.
The feature is optimized for low-latency lookups, which makes it suitable for interactive search boxes where requests are sent frequently.
However, it is important to understand its limitations. Completion suggestions are based on prefixes. They are not intended to provide general full-text search, arbitrary substring matching, or spelling correction as their primary purpose. Elasticsearch provides other suggesters, such as the Term and Phrase suggesters, for different search problems.
Creating an Elasticsearch Index With a Completion Field
The first step is to define a completion field in the index mapping.
In this example, we will build an autocomplete feature for an online shopping application.
Create an index named products:
PUT products
{
"mappings": {
"properties": {
"productId": {
"type": "keyword"
},
"productName": {
"type": "text"
},
"category": {
"type": "keyword"
},
"price": {
"type": "float"
},
"suggest": {
"type": "completion"
}
}
}
}
The mapping contains five fields.
The productId field stores the product identifier. The productName field supports normal text search, while category is used for exact category filtering. The price field stores the product price.
The suggest field is the important part of this implementation. Its type is completion, which tells Elasticsearch to build the specialized data structure required for autocomplete suggestions.
Keeping productName and suggest as separate fields is useful because they serve different purposes. The text field supports regular search queries, while the completion field supports fast prefix-based suggestions.
The completion field uses the simple analyzer by default. You can configure a different analyzer when the application's language and tokenization requirements need different behavior.
Indexing Product Suggestions
After creating the index, add products along with their suggestion inputs.
Elasticsearch allows multiple suggestion inputs to be associated with one document. Each input can also have a weight that influences its ranking.
For example:
POST products/_doc/1
{
"productId": "P1001",
"productName": "Laptop",
"category": "Computers",
"price": 65000,
"suggest": [
{
"input": "Laptop",
"weight": 10
},
{
"input": "Notebook Computer",
"weight": 6
},
{
"input": "Portable Laptop",
"weight": 5
}
]
}
Another product can be indexed as follows:
POST products/_doc/2
{
"productId": "P1002",
"productName": "Laptop Stand",
"category": "Accessories",
"price": 1500,
"suggest": [
{
"input": "Laptop Stand",
"weight": 8
},
{
"input": "Adjustable Laptop Stand",
"weight": 7
}
]
}
The input property contains the actual text that Elasticsearch should suggest. The weight property provides a ranking value.
A higher weight makes a suggestion more relevant for ranking purposes when matching inputs compete with one another.
For example, the main product name can receive a higher weight than an alternative search phrase. This helps the application prioritize commonly used product names.
You can also use a shorthand format:
POST products/_doc/3
{
"productId": "P1003",
"productName": "Wireless Keyboard",
"category": "Accessories",
"price": 2200,
"suggest": [
"Wireless Keyboard",
"Bluetooth Keyboard",
"Computer Keyboard"
]
}
The shorthand format is convenient when suggestions do not require individual weights. If you need to assign weights to individual inputs, use the object format.
Querying Suggestions With the Completion Suggester
Once the products are indexed, the application can request suggestions using the _search API.
For example, when a user types "lap", execute the following query:
POST products/_search
{
"suggest": {
"product-suggestions": {
"prefix": "lap",
"completion": {
"field": "suggest",
"size": 5
}
}
}
}
The request contains three important parts.
The product-suggestions property is the name of the suggestion request. It can be any meaningful name chosen by the application.
The prefix property contains the text entered by the user. In this example, Elasticsearch looks for suggestions beginning with "lap".
The completion object identifies the completion field and controls the number of suggestions returned.
The size property is optional and defaults to five suggestions.
The response contains a suggest section with matching options:
{
"suggest": {
"product-suggestions": [
{
"text": "lap",
"offset": 0,
"length": 3,
"options": [
{
"text": "Laptop",
"_id": "1",
"_score": 10.0
},
{
"text": "Laptop Stand",
"_id": "2",
"_score": 8.0
}
]
}
]
}
}
The options array contains the suggestions returned by Elasticsearch.
The text property contains the suggested input, while _score reflects the configured suggestion weight.
The application can display these options directly below the search box. When a user selects a suggestion, the application can execute a normal search using the selected text.
One important detail is that completion suggestions are near-real-time. Newly indexed suggestions become available after the index refresh makes them searchable.
Returning Only the Required Fields
By default, completion suggestions can include the full source document in each option.
For a product catalog containing descriptions, specifications, images, and other fields, returning the complete document for every suggestion may increase response size and unnecessary network traffic.
Use source filtering to return only the fields required by the autocomplete interface.
POST products/_search
{
"_source": [
"productId",
"productName",
"category"
],
"suggest": {
"product-suggestions": {
"prefix": "lap",
"completion": {
"field": "suggest",
"size": 5
}
}
}
}
This is useful when the application needs only the product identifier, product name, and category to render the suggestion list.
The suggest endpoint does not support source filtering in the same way. Using the search endpoint allows the application to combine suggestions with source filtering.
Reducing the returned source is especially useful when autocomplete requests are executed after every meaningful change to the search input.
Removing Duplicate Suggestions
A product may have several documents containing the same suggestion input. This can happen when an application stores multiple product variants, regional records, or alternative catalog entries.
For example, the word "Laptop" might appear in several product documents.
Without duplicate filtering, the application could display the same suggestion multiple times.
Elasticsearch provides skip_duplicates to remove duplicate suggestion text from the results.
POST products/_search
{
"suggest": {
"product-suggestions": {
"prefix": "lap",
"completion": {
"field": "suggest",
"size": 10,
"skip_duplicates": true
}
}
}
}
This tells Elasticsearch to return distinct suggestion text rather than multiple copies of the same input.
However, duplicate filtering can require Elasticsearch to visit more candidates to find the requested number of unique suggestions. This may make the query slower.
Use it when duplicate suggestions are a genuine user-interface problem, and measure its effect with realistic catalog data.
Also remember that duplicate suggestion text and duplicate products are different concepts. Two products can legitimately have similar names while still representing separate records. The application should decide whether to display distinct names, product variants, or individual products.
Handling Typing Mistakes With Fuzzy Completion
Users do not always enter search terms correctly.
For example, someone searching for "Wireless Keyboard" might type "wireles".
A normal prefix completion query may not return the intended suggestion because the input does not match the indexed prefix.
Elasticsearch supports fuzzy completion to handle certain typing mistakes.
POST products/_search
{
"suggest": {
"product-suggestions": {
"prefix": "wireles",
"completion": {
"field": "suggest",
"size": 5,
"fuzzy": {
"fuzziness": "AUTO"
}
}
}
}
}
The fuzzy option allows Elasticsearch to consider suggestions that differ from the entered prefix by a limited number of character edits.
You can also configure individual fuzzy settings:
POST products/_search
{
"suggest": {
"product-suggestions": {
"prefix": "wirless",
"completion": {
"field": "suggest",
"size": 5,
"fuzzy": {
"fuzziness": 2,
"transpositions": true,
"min_length": 3,
"prefix_length": 1
}
}
}
}
}
The settings control how Elasticsearch handles spelling differences.
fuzziness controls the allowed edit distance.
transpositions determines whether swapping adjacent characters counts as one edit.
min_length defines the minimum input length before fuzzy matching is used.
prefix_length specifies how many initial characters must match exactly.
Fuzzy matching is useful for improving the search experience, but it should be used carefully. It can increase the number of candidates Elasticsearch needs to consider.
For a large product catalog, enable fuzzy matching only when the user has entered enough characters to make the results useful. Very short prefixes can produce broad and potentially irrelevant suggestions.
Filtering Suggestions With Category Contexts
A general product search box may need to display suggestions from the entire catalog. However, some applications have multiple search experiences.
For example, an online shopping application may have separate sections for:
Electronics
Clothing
Books
Home Appliances
A user searching inside the Books section should not receive suggestions from unrelated product categories.
Elasticsearch supports category contexts for completion fields.
First, define a context mapping:
PUT products_with_context
{
"mappings": {
"properties": {
"productName": {
"type": "text"
},
"category": {
"type": "keyword"
},
"suggest": {
"type": "completion",
"contexts": [
{
"name": "product_category",
"type": "category",
"path": "category"
}
]
}
}
}
}
The product_category context reads category values from the category field.
Next, index a product:
POST products_with_context/_doc/1
{
"productName": "Laptop",
"category": "Electronics",
"suggest": [
"Laptop",
"Portable Computer"
]
}
Another product can be indexed with a different category:
POST products_with_context/_doc/2
{
"productName": "Laptop Bag",
"category": "Accessories",
"suggest": [
"Laptop Bag",
"Computer Bag"
]
}
Now query suggestions using a category context:
POST products_with_context/_search
{
"suggest": {
"product-suggestions": {
"prefix": "lap",
"completion": {
"field": "suggest",
"size": 5,
"contexts": {
"product_category": [
{
"context": "Electronics"
}
]
}
}
}
}
}
The query returns suggestions associated with the Electronics category.
Contexts can also be used for boosting. For example, the application can give suggestions from a preferred category a higher score without excluding suggestions from other categories.
Context mappings must be supplied when indexing and querying a context-enabled completion field. They increase the size of the completion index, so use them only when the application needs category-based filtering or boosting.
Elasticsearch supports category and geo contexts for completion suggesters. A completion field can have multiple context mappings, subject to the documented limit.
Using Weights to Control Suggestion Ranking
Suggestion ranking is important because the application should display the most useful options first.
Consider an online shopping application where the search prefix is "lap".
The catalog might contain:
Laptop
Laptop Stand
Laptop Cooling Pad
Laptop Backpack
Laptop Screen Protector
The application may want to prioritize popular products or commonly selected search phrases.
You can assign different weights during indexing:
POST products/_doc/4
{
"productId": "P1004",
"productName": "Laptop Cooling Pad",
"category": "Accessories",
"price": 1800,
"suggest": {
"input": [
"Laptop Cooling Pad",
"Laptop Cooler"
],
"weight": 4
}
}
A frequently searched product can receive a higher weight:
POST products/_doc/5
{
"productId": "P1005",
"productName": "Laptop Backpack",
"category": "Accessories",
"price": 2500,
"suggest": {
"input": [
"Laptop Backpack",
"Computer Backpack"
],
"weight": 9
}
}
When matching suggestions compete, the weight influences their scores.
Weights should come from meaningful application signals, such as product popularity, search frequency, or business relevance. Avoid assigning arbitrary high values to every new product, because doing so removes the value of ranking.
Also consider that weights are associated with indexed suggestions. If popularity changes over time, the application needs a strategy to update the indexed suggestion information.
Understanding Completion Performance and Memory Usage
The Completion Suggester is optimized for fast lookups, but that speed comes with a resource trade-off.
Its completion data structure is stored in memory. This allows Elasticsearch to retrieve suggestions quickly without relying on a full document scan for every keystroke.
However, a large completion index can consume significant JVM heap memory.
The number of suggestions, the length of each input, the number of completion fields, and the configured contexts all influence the amount of memory required.
For example, indexing every product description as a completion input is usually a poor design. Descriptions can be long and contain many words that do not represent useful autocomplete options.
Instead, index focused suggestion values such as product names, popular alternative names, and commonly searched phrases.
The completion field also supports the max_input_length mapping parameter. Its default value is 50 UTF-16 code points. This setting limits the length of each input during indexing and helps prevent very long values from unnecessarily increasing the completion structure.
You should also consider shard design. Completion queries spanning multiple shards require additional coordination and document-fetch work. Elasticsearch documentation recommends a single-shard index for the best completion performance when practical. If a large completion index creates excessive heap pressure, splitting the index into multiple shards may be more appropriate than forcing the entire workload into one shard.
Monitor completion field memory usage through index statistics and test with realistic data volumes before choosing the final shard configuration.
Integrating Completion Suggestions Into an Application
Elasticsearch provides the backend capability, but the application still needs to manage the user interaction.
A typical autocomplete workflow looks like this:
The user enters text into the search box.
The application waits briefly for the user to stop typing.
The frontend sends the current prefix to the application API.
The API executes a completion query against Elasticsearch.
Elasticsearch returns the matching suggestions.
The API returns only the fields required by the frontend.
The frontend displays the suggestion list.
The user selects a suggestion and the application executes the full search.
A short debounce interval can prevent the application from sending a request for every individual keystroke. The appropriate interval depends on the application's responsiveness requirements and network conditions.
The frontend should also cancel or ignore outdated requests. For example, if a user types "lap" and then quickly changes the input to "laptop", the response for "lap" may arrive after the response for "laptop". Without request coordination, the older response could overwrite the more relevant suggestions.
The API should validate prefix length, limit the number of returned suggestions, and avoid exposing unnecessary source fields.
For applications that support multiple users or restricted catalogs, remember that completion contexts are not a substitute for authorization. If suggestions must be restricted by tenant, user permissions, or confidential data ownership, enforce those restrictions in the application architecture and ensure that users cannot access suggestions outside their authorization scope.
Common Design Mistakes to Avoid
Several implementation choices can reduce the usefulness or performance of autocomplete.
Indexing entire descriptions
Long descriptions create large completion structures and often produce irrelevant suggestions. Index meaningful product names and search phrases instead.
Using completion for every search requirement
Completion is designed for prefix-based navigation. Use normal text queries for full-text relevance, and other suggesters when spelling correction or phrase suggestions are the actual requirement.
Returning too many suggestions
A search box generally does not need hundreds of options. Keep the result size small and relevant so that the response remains efficient and the interface is easy to use.
Ignoring duplicate inputs
Multiple documents may contain the same suggestion text. Decide whether duplicates should be displayed or filtered, and test the performance impact of skip_duplicates.
Overusing fuzzy matching
Fuzzy matching is helpful for misspellings, but enabling it for very short prefixes can return irrelevant results and increase processing work.
Ignoring heap usage
The completion data structure is memory-resident. Monitor the size of completion indexes and avoid indexing unnecessary values or contexts.
Conclusion
Elasticsearch Completion Fields provide an efficient way to build autocomplete and search-as-you-type experiences. By defining a completion mapping, indexing meaningful suggestion inputs, and querying them through the Completion Suggester, developers can return relevant options as users enter text.
Weights help control ranking, skip_duplicates removes repeated suggestion text, fuzzy matching handles common typing mistakes, and category or geo contexts allow suggestions to be filtered or boosted.
The most important design decision is selecting the right suggestion data. Keep inputs focused, avoid indexing unnecessary descriptions, choose weights based on meaningful signals, and monitor the memory used by completion structures.
For production applications, combine Elasticsearch completion queries with frontend debouncing, request cancellation, source filtering, and proper authorization. This creates a responsive search experience without turning every keystroke into an expensive full-text search operation.
Join the conversation! Your thoughts help the community grow.