Did you mean
The term suggester corrects a word against the vocabulary actually indexed in a field. Use it when a search returns nothing, to offer the spelling that would have worked.
Ask for a correction
await es.search({
index: 'shop.products', size: 0,
suggest: {
did_you_mean: { text: 'marathn', term: { field: 'name' } }
}
})
// suggest.did_you_mean[0]
// text: 'marathn', offset: 0, length: 7
// options: [ { text: 'marathon', score: 0.857 } ]Each entry is one word of your input, with its offset and length so you can splice a correction back into the original string. Options come back best first; the score is one minus the edit distance over the word length.
Correct every word, or only unknown ones
suggest_mode defaults to missing: a word the index already holds gets no options, which is what a search box wants. always returns near neighbours even for a word that exists, which is what you want for query expansion.
term: { field: 'name', suggest_mode: 'always', size: 3 }A search box, end to end
Run the search; if it returns nothing, ask for a correction and offer it.
const res = await es.search({ index: 'shop.products',
query: { match: { name: q } },
suggest: { fix: { text: q, term: { field: 'name' } } }
})
if (res.hits.total.value === 0) {
const best = res.suggest.fix[0]?.options[0]?.text
if (best) console.log(`Did you mean ${best}?`)
}What it does not return
Elasticsearch puts a freq on every option. That number lives somewhere this API cannot reach, so the field is omitted rather than invented. If you rank suggestions yourself, rank on score. For the same reason suggest_mode: popular, which is defined by frequency, is refused.
The phrase and completion suggesters are refused by name — there is no executor for either, and a silent empty result would read as "no suggestions" rather than "not supported".
Elasticsearch is a trademark of Elasticsearch B.V., registered in the U.S. and in other countries. OriginChainDB is not affiliated with, endorsed by, or sponsored by Elasticsearch B.V. OriginChainDB implements a compatible HTTP API so that existing Elasticsearch clients can talk to it; it does not distribute Elasticsearch software.