MongoDB full-text search

Free MongoDB courses: Ali Cloud University - developers classroom

The establishment of a full-text search index for each word, indicating the number and location of the word appears in the article, when a user query, the search program to find the index previously established, and feedback the results to find the way to retrieve the user.

This process is similar to the process of search words by searching the word list dictionary.

MongoDB from the 2.4 version began to support full-text search, currently supports 15 languages ( temporarily does not support Chinese ) full-text index.

danish

dutch

english

finnish

french

german

hungarian

italian

norwegian

portuguese

romanian

russian

spanish

swedish

turkish

 

Enable full-text search

MongoDB in 2.6 or later full-text search is enabled by default, if you use the previous version, you need to use the following code to enable full-text search :

>db.adminCommand({setParameter:true,textSearchEnabled:true})


Or use the command:

mongod --setParameter textSearchEnabled=true


Create a full-text index

Consider the following posts document data collection, including the content of the article ( POST_TEXT ) and labels (Tags) :

{
   "post_text": "enjoy the mongodb articles on Openketang",
   "tags": [
      "mongodb",
      "openketang"
   ]}


我们可以对 post_text 字段建立全文索引,这样我们可以搜索文章内的内容:

>db.posts.ensureIndex({post_text:"text"})


 使用全文索引

现在我们已经对 post_text 建立了全文索引,我们可以搜索文章中的关键词 openketang

>db.posts.find({$text:{$search:"openketang"}})


以下命令返回了如下包含 runoob 关键词的文档数据:

{ 
   "_id" : ObjectId("53493d14d852429c10000002"), 
   "post_text" : "enjoy the mongodb articles on Openketang", 
   "tags" : [ "mongodb", "openketang" ]}


如果你使用的是旧版本的 MongoDB,你可以使用以下命令:

>db.posts.runCommand("text",{search:"openketang"})


使用全文索引可以提高搜索效率。

 

删除全文索引

删除已存在的全文索引,可以使用 find 命令查找索引名:

>db.posts.getIndexes()


通过以上命令获取索引名,本例的索引名为post_text_text,执行以下命令来删除索引:

>db.posts.dropIndex("post_text_text")


 

免费MongoDB课程:阿里云大学——开发者课堂


Guess you like

Origin blog.51cto.com/13730592/2404735