我从几天前就在 Google 上搜索,我尝试了很多方法,但我仍然无法对我的用户集合执行良好的全文搜索。
我尝试过 ElasticSearch,但几乎无法查询和分页...
我为 Mongoose 尝试了许多插件,例如 ElMongo、mongoose-full-text、Mongoosastic 等...每个人的文档都非常糟糕,我不知道如何执行良好的全文搜索。
所以,我的收藏是一个普通的收藏:
user = {
name: String,
email: String,
profile: {
something: String,
somethingElse: String
}
}
我在带有简单 POST
的页面中有一个搜索输入,如果我键入 hello world
,我需要在整个集合字段中搜索匹配的单词我的搜索查询并获得结果。
如果有选项来处理分页,比如每页 10 个项目或其他东西,那就太好了......
实现这一目标的最佳解决方案是什么?我将 MongoDB 2.6.* 与 Mongoose、NodeJS 和 ExpressJS 一起使用。
谢谢。
最佳答案
您可以添加 text index添加到您的 Mongoose 模式定义中,让您可以使用 $text
find
查询中的运算符来搜索包含在文本索引中的所有字段。
要创建一个索引以支持对 name
和 profile.something
等文本搜索:
var schema = new Schema({
name: String,
email: String,
profile: {
something: String,
somethingElse: String
}
});
schema.index({name: 'text', 'profile.something': 'text'});
或者如果您想在索引中包含所有字符串字段,请使用 '$**'
通配符:
schema.index({'$**': 'text'});
这将使您能够执行分页文本搜索查询,例如:
MyModel.find({$text: {$search: searchString}})
.skip(20)
.limit(10)
.exec(function(err, docs) { ... });
更多详情,请阅读全文 MongoDB Text Indexes文档。
关于javascript - 在 MongoDB 和 Mongoose 中执行全文搜索的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28775051/