在MongoDB和Mongoose中执行全文搜索的最佳方式 [英] Best way to perform a full text search in MongoDB and Mongoose

查看:152
本文介绍了在MongoDB和Mongoose中执行全文搜索的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Google上搜索了几天,我尝试了很多东西,但是我仍然无法在我的用户集合上执行一个很好的全文搜索。



我尝试过ElasticSearch但是很不可能查询和分页...



我尝试了许多插件,如ElMongo,mongoose全文,Mongoosastic等等,不好的记录,我不知道如何执行一个好的全文搜索。



所以,我的收藏是一个正常的集合:

  user = {
name:String,
email:String,
profile:{
something:String,
somethingElse:String
}
}

我有一个搜索输入在一个简单的 POST 的页面中,如果我键入 hello world 我需要的是搜索整个集合字段我的搜索查询的匹配单词,并得到结果。



这将是非常好的有选项来处理分页ke每页10个项目或某事...



达到此目的的最佳解决方案是什么?我使用MongoDB 2.6。*与Mongoose,NodeJS和ExpressJS。



谢谢。

解决方案

您可以添加文字索引到您的Mongoose模式定义,让您可以使用 $ text 运算符在 find 查询中搜索文本索引中包含的所有字段。 p>

要创建支持文本搜索的索引,例如 name profile.something

  var schema = new Schema({
name:String,
电子邮件:String,
个人资料:{
something:String,
somethingElse:String
}
});
schema.index({name:'text','profile.something':'text'});

或者如果要在索引中包含所有字符串字段,请使用 '$ **'通配符:

  schema.index({'$ **'文本'}); 

这将使您能够执行分页文本搜索查询,如:

  MyModel.find({$ text:{$ search:searchString}})
.skip(20)
.limit(10)
.exec(function(err,docs){...});


I'm searching on Google since days and I tried many things but I still can not perform a good full text search on my user collection.

I tried ElasticSearch but was pretty impossible to query and paginate...

I tried many plugins for Mongoose like ElMongo, mongoose-full-text, Mongoosastic, etc... everyone are really bad documented and I don't know how to perform a good full text search.

So, my collection is a normal collection:

user = {
  name: String,
  email: String,
  profile: {
    something: String,
    somethingElse: String
  }
}

I have a search input in a page with a simple POST, if I type hello world what I need is to search on the entire collection fields the matching words of my search query and get the results.

It will be really nice also to have options to handle a pagination like 10 items per page or something...

What is the best solution to achieve this? I'm using MongoDB 2.6.* with Mongoose, NodeJS and ExpressJS.

Thanks.

解决方案

You can add a text index to your Mongoose schema definition that lets you use the $text operator in your find queries to search all fields included in the text index.

To create an index to support text search on, say, name and profile.something:

var schema = new Schema({
  name: String,
  email: String,
  profile: {
    something: String,
    somethingElse: String
  }
});
schema.index({name: 'text', 'profile.something': 'text'});

Or if you want to include all string fields in the index, use the '$**' wildcard:

schema.index({'$**': 'text'});

This would enable you to performed a paged text search query like:

MyModel.find({$text: {$search: searchString}})
       .skip(20)
       .limit(10)
       .exec(function(err, docs) { ... });

这篇关于在MongoDB和Mongoose中执行全文搜索的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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