使用 Mongodb 进行模糊搜索? [英] Fuzzy Searching with Mongodb?

查看:33
本文介绍了使用 Mongodb 进行模糊搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设法在我的 mongodb 应用程序中设置了一个搜索功能.请参阅下面的代码.这非常有效,但是它只返回精确的结果.我将如何更改我的代码以使其接受更多模糊"的搜索结果?谢谢!

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});
       }
    });
});

推荐答案

我相信要进行模糊"搜索,您需要使用正则表达式.这应该可以完成您正在寻找的内容(escapeRegex 函数源 here):

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 });
           }
       }); 
    }
}

话虽如此,您的应用程序在通过正则表达式查询 mongo 时可能会遇到性能问题.使用像 search-index 这样的库进行搜索可以帮助优化应用程序的性能,添加搜索词干的好处(比如从find"返回found").

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").

更新:我的原始答案包括一个简单的正则表达式,它会使您的应用程序容易受到正则表达式 DDoS 攻击.我已经更新了一个安全"的转义正则表达式.

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.

这篇关于使用 Mongodb 进行模糊搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆