Skip to main content

🦸 Turbocharge your search with fuzzy matching

Next, you'll implement fuzzy matching also known as approximate string matching. Fuzzy matching helps identify two texts that are approximately similar but not the same.

Try changing the query value to “hary poter”. No documents are returned. Using fuzzy matching you will be able to find the Harry Potter documents even if you misspell the name in the query.

In the aggregation builder, scroll up to Stage 1 and replace the code with the following.

{
index: "fulltextsearch",
text: {
query: "hary poter",
path: "title",
fuzzy: {
maxEdits: 2
}
}
}

You can now see that all documents with title similar to the search terms show up in the results. You can adjust the maxEdits parameter to specify how similar the returned documents can be to the query.

Add it to your application

There is a method ready for you to use in the server/controllers/movies.mjs file. Open up the file and find the fuzzySearch method. Replace the code with your new aggregation pipeline that will do fuzzy searching.

You can find more about all the parameters for the text search operator in the documentation.

Answer
  async fuzzySearch(searchTerm) {
const movies = await collection
.aggregate([
{
$search: {
index: "default",
text: {
query: searchTerm,
path: {
wildcard: "*",
},
fuzzy: {
maxEdits: 2,
},
},
},
},
{
$project: {
title: 1,
year: 1,
"imdb.rating": 1,
fullplot: 1,
poster: 1,
released: 1,
genres: 1
},
},
{
$limit: 20
}
]).toArray();

return movies;
}