Fuzzy search with Mongodb?

I was able to configure the search function in my mongodb application. See code below. This works very well, however it only returns accurate results. How can I change my code to 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}); } }); }); 
+9
source share
3 answers

I believe that for a "fuzzy" search you will need to use a regular expression. This should accomplish what you are looking for (source of the escapeRegex function 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 }); } }); } } 

However, your application may experience performance issues when querying mongo for regular expression. Using a library, such as search-index for search, can help optimize the performance of your application, with the added benefit of searching for word stems (for example, returning “found” from “find”).


UPDATE: my initial answer included a simple regular expression that would leave your application vulnerable to a regular DDoS attack . I updated the "safe" escaped regex.

+21
source

I know this is an old branch, but I created a plugin based on this article .

Mongoose-fuzzy search

(It uses the $text query operator $text instead of $regex , for faster results)

In the example below, only event search based on name and city

 const mongoose_fuzzy_searching = require('mongoose-fuzzy-searching'); const schema = { title: { type: String, trim: true, required: true, }, description: { type: String, trim: true, }, city: { type: String, }, address: { type: String, } }; const EventsSchema = mongoose.Schema(schema); EventsSchema.plugin(mongoose_fuzzy_searching, {fields: ['title', 'city']}); const Events = mongoose.model('Events', EventsSchema); Events.fuzzySearch('Nodejs meetup').then(console.log).catch(console.error); 
+1
source

@Vassilis Pallas, is there any way to use your mongoose_fuzzy_searching without using mongoose? I have to add a fuzzy search to an existing project, and it does not have a mongoose.

0
source

All Articles