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

查看:172
本文介绍了用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函数源此处):

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时,您的应用程序可能会遇到性能问题.使用搜索索引之类的库进行搜索可以帮助优化应用程序的性能,并增加了搜索词干的好处(例如从查找"返回找到").

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

更新:我的原始答案包括一个简单的常规扩展名,使您的应用程序容易受到 regex 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天全站免登陆