Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

javascript - Best way to perform a full text search in MongoDB and Mongoose

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...