I have managed to set up a search feature in my mongodb app. See the code below. This works very well however it only returns exact results. How would I change my code to make it accept more "fuzzy" search results? Thanks!
router.get("/", function(req, res){ if (req.query.search) { Jobs.find({"name": req.query.search}, function(err, foundjobs){ if(err){ console.log(err); } else { res.render("jobs/index",{jobs:foundjobs}); } }); } Jobs.find({}, function(err, allJobs){ if(err){ console.log(err); } else { res.render("jobs/index",{jobs:allJobs}); } }); });
fuzzy text searching requires the use of a mongodb text index which can be easily created like this: await DB. Index<Person>() . Key(p => p.Name, KeyType.
A fuzzy search searches for text that matches a term closely instead of exactly. Fuzzy searches help you find relevant results even when the search terms are misspelled. To perform a fuzzy search, append a tilde (~) at the end of the search term.
Fuzzy searches find words or phrases (values) that are similar, but not necessarily identical, to other words or phrases (values). This type of search has many uses, such as finding sequence errors, spelling errors, transposed characters, and others we'll cover later.
For example, if a user types "Misissippi" into Yahoo or Google -- both of which use fuzzy matching -- a list of hits is returned along with the question, "Did you mean Mississippi?" Alternative spellings and words that sound the same but are spelled differently are given.
I believe that to do "fuzzy" search you will need to use regex. This should accomplish what you're looking for (escapeRegex function source here):
function escapeRegex(text) { return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }; router.get("/", function(req, res) { if (req.query.search) { const regex = new RegExp(escapeRegex(req.query.search), 'gi'); Jobs.find({ "name": regex }, function(err, foundjobs) { if(err) { console.log(err); } else { res.render("jobs/index", { jobs: foundjobs }); } }); } }
That being said, your application can experience performance issues when querying mongo by regex. Using a library like search-index for search could help optimize your application's performance, with the added benefit of searching word stems (like returning "found" from "find").
UPDATE: My original answer included a simple regular exression that would leave your application vulnerable to a regex DDoS attack. I've updated with a "safe" escaped regex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With