MongoDB full text search index: error: too many text index for, why?

不想你离开。 提交于 2019-12-05 07:55:36

MongoDB only allows one text-index per collection.

But you can use a text-index which spans multiple fields:

db.collection.ensureIndex( {
    description: "text",
    title: "text"
} );

That way you will get results when the phrase you are searching for is found in either. When this is not what you want, like when you have two search-queries which each return results from one of the fields but not the other, you have two options.

  1. use a multi-field text index, but discard the results which come from the wrong field on the application layer.
  2. extract one of the two fields to a different collection. The documents in that collection could either contain full copies, redacted copies or just the field you index and the _id of the original document.

To create a text based index on a key, use command db.collectionName.ensureIndex({'textColumnName': 'text'}). After this index is applied, use the search commands to search for a word i.e. db.collectionName.find({$text: {$search:'your text here'}}). There is a text score based on which the results are ranked, to see it project it in the score key like this : db.collectionName.find({$text: {$search:'your text here'}}, {score: {$meta: 'textScore'}}).sort({score: {$meta: 'textScore'}}).

If we create a text index on the title field of the movies collection, and then perform the text search db.movies.find( { $text : { $search : "Big Lebowski" } } ). The following documents will be returned, assuming they are in the movies collection:

  • { "title" : "The Big Lebowski" , star: "Jeff Bridges" }

  • { "title" : "Big" , star : "Tom Hanks" }

  • { "title" : "Big Fish" , star: "Ewan McGregor" }

This is because, there will be a ***logical OR***ing on Big & Lebowski.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!