Did you mean
A term suggestion offers a spelling close to words already in the index. Use it after an empty search to give the person another query to try. A suggestion is a spelling option, not a matching document.
Complete the Elasticsearch quickstart to connect the client and create shop.products. Index a name containing “marathon” before trying the “marathn” example below. Suggestions depend on words actually in that field.
- Notice an unhelpful searchFor example, a misspelled term returns no useful hits.
- Request term suggestionsCompare the term with words in the indexed field.
- Offer a correctionLet the application or user choose the suggested word.
- Run the corrected searchUse the chosen word to retrieve actual documents.
Ask for a correction
await es.search({
index: 'shop.products',
body: {
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: missing suggests alternatives only for words absent from the index. always also suggests alternatives for known words. Use missing for a spelling correction; use always when you deliberately want to broaden a query.
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 { body: res } = await es.search({
index: 'shop.products',
body: {
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
The response does not include document frequency: how many documents contain each option. Rank available suggestions by score. The popular suggestion mode requires frequency information and 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".
- Fuzzy matching — Typo tolerance inside the query itself, rather than as a correction.
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.