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

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

问题描述

几天以来我一直在 Google 上进行搜索,我尝试了很多方法,但仍然无法对我的用户集合进行良好的全文搜索.

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.

我尝试了 ElasticSearch,但几乎无法查询和分页...

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

我尝试了很多 Mongoose 插件,例如 ElMongo、mongoose-full-text、Mongoosastic 等……每个人的文档都非常糟糕,我不知道如何进行良好的全文搜索.

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

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

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.

如果有处理分页的选项,比如每页 10 个项目之类的,那就太好了……

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

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

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

谢谢.

推荐答案

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

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.

创建一个索引来支持文本搜索,比如,nameprofile.something:

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 文本索引文档.

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

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

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