Building Search API with ElasticSearch — Part 07: “Did you mean”

André Coelho
3 min readJul 12, 2022

--

The term correction suggestion is a very important feature for the search engine. In the post “Create a simple “did you mean” — ElasticSearch” a term correction solution was implemented using the Phrase suggester.
We will use the same approach to add this functionality to our search engine.

In the same way that we created the suggestion in the post “Create a simple “did you mean” — ElasticSearch”, we will create a new field that will be responsible for suggesting the corrections.

Due to an error in the Java API Client it is not possible to deserialize the results and use the Phrase Suggester. This bug has already been opened in Git and we will be waiting for a new release with the correction.
Meanwhile I did all the implementation using the RestHighClientLevel but left the same implementation with the Java API Client. So we have both implementations.

Java Code

The first thing to do is create a Phrase suggester object by adding the desired parameters to get the best results. Once created, this object will be set in SearchSourceBuilder in the suggester property.

If elastic finds a suggestion for the given term, we must extract the options in SearchResponse. As I said, it will return a list of options, I will only want to display the first option as it will be the closest to being the correct suggestion.

Once the suggestion is retrieved, we will set the “suggestion” property in our MovieCatalogDTO.

Running tests

Let’s test our “did you mean”, we’ll look for some intentionally misspelled terms and see the suggestions provided by our search engine.

Search by term "shawshank redeption":

Suggestion "Shawshank Redemption"

Search by term "inseption"

Suggestion "Inception"

Search by term "Forest gump"

Suggestion "Forrest Gump"

We are close to finalizing functionality in our search API, the next will be about Sorting. Until the next post!!

Building Search API with ElasticSearch — Part 01: Preparing the environment
Building Search API with ElasticSearch — Part 02: Pagination
Building Search API with ElasticSearch — Part 03: Autocomplete
Building Search API with ElasticSearch — Part 04: Search Query
Building Search API with ElasticSearch — Part 05: Simple Facets
Building Search API with ElasticSearch — Part 06: Filters
Building Search API with ElasticSearch — Part 07: “Did you mean”
Building Search API with ElasticSearch — Part 08: Sort results
Building Search API with ElasticSearch — Part 09: Recommendation with More Like This Query
Building Search API with ElasticSearch — Part 10: Front-End
Building Search API with ElasticSearch — Part 11: Elastic APM

--

--

André Coelho

Developer of web and mobile systems. Enthusiast in the area of ​​automation and electronics and I have hobbie music.