Backend Engineer: Tuning Elasticsearch & OpenSearch for Sub-10ms Prefix, Edge N-Gram & Case-Insensitive String Lookups
Running runtime wildcard queries (`*4092-AB*`) or regex filters across millions of SKU codes, serial numbers, and customer emails in Elasticsearch or OpenSearch forces expensive term dictionary scans that spike cluster CPU to 100%. Conversely, applying the default English standard analyzer splits hyphenated part numbers (`"SN74HC595N-TR"`) in ways that break exact prefix autocomplete. As a Backend Engineer, I design custom index-time Edge N-Gram tokenizers, keyword normalizers, and multi-field mappings that execute complex substring and prefix lookups in under 10 milliseconds.
1. Index-Time Edge N-Grams + Search-Time `lowercase` Analyzer Separation
A critical Elasticsearch rule for instant typeahead is using an `edge_ngram` tokenizer at index time (`min_gram: 2`, `max_gram: 20`) while pairing it with a standard `lowercase` keyword analyzer at search time. If you apply `edge_ngram` at search time as well, a user query for `"SN74HC"` gets shattered into `"SN"`, `"SN7"`, `"SN74"`, polluting precision with thousands of unrelated two-letter matches:
{
"settings": {
"analysis": {
"normalizer": {
"folded_keyword_normalizer": {
"type": "custom",
"filter": ["lowercase", "asciifolding"]
}
},
"tokenizer": {
"sku_edge_ngram_tokenizer": {
"type": "edge_ngram",
"min_gram": 2,
"max_gram": 20,
"token_chars": ["letter", "digit"]
}
},
"analyzer": {
"sku_index_analyzer": {
"type": "custom",
"tokenizer": "sku_edge_ngram_tokenizer",
"filter": ["lowercase", "asciifolding"]
},
"sku_search_analyzer": {
"type": "custom",
"tokenizer": "keyword",
"filter": ["lowercase", "asciifolding"]
}
}
}
},
"mappings": {
"properties": {
"sku": {
"type": "keyword",
"normalizer": "folded_keyword_normalizer",
"fields": {
"prefix": {
"type": "text",
"analyzer": "sku_index_analyzer",
"search_analyzer": "sku_search_analyzer"
}
}
}
}
}
}
2. Boosting Exact Keyword Hits Above N-Gram Prefix Matches
By querying a `bool.should` clause that boosts `sku` (`boost: 10.0`) above `sku.prefix` (`boost: 1.5`), an exact match for a part number always ranks at position #1 while partial prefixes populate instant autocomplete suggestions—integrating cleanly with our asynchronous PostgreSQL-to-Elasticsearch sync pipeline and electronic component fuzzy matching architecture.
Need a Backend Engineer to tune your Elasticsearch or OpenSearch analyzers and relevance scoring? Book a 1-Day Engineering Sprint.