在 MongoDB 和 Mongoose 中执行全文搜索的最佳方法

我在谷歌搜索,因为天,我尝试了很多事情,但我仍然不能执行一个良好的全文搜索我的用户集。

我试过弹性搜索,但是很难查询和分页..。

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.

因此,我的收藏是一个正常的收藏:

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

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

它将真的很好,也有选项来处理一个分页,如每页10个项目或东西..。

实现这一点的最佳解决方案是什么? 我使用 MongoDB 2.6. * 和 Mongoose、 NodeJS 和 ExpressJS。

谢谢。

92228 次浏览

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

For more details, read the full MongoDB Text Indexes documentation.

This is not an extra answer but an addUp, but if the above answer by JohnnyHK is giving you an empty array [] .

  1. Try something basic first without limit and skip

    const results = await MyModel.find({ $text: { $search: "text" } });

  2. Please check if the index was created properly using mongosh using db.stories.getIndexes() or compass GUI both attached. Else create one via COMPASS GUI or via mongosh using docs

compasss

  1. Then try changing searchText multiple times and try.
  2. Even after all this it took me 7- 8 runs of same code to get proper results,