A brief analysis of MongoDB full text retrieval

  • 2021-01-22 08:13:03
  • OfStack

Full-text retrieval establishes an index for each word, indicating the number and position of the word in the article. When the user queries, the retrieval program searches according to the pre-established index, and feeds back the search results to the user.

This process is similar to the process of looking up words by searching the word table in a dictionary.

MongoDB has supported full-text search since version 2.4 and currently supports full-text indexing in 15 languages.

danish dutch english finnish french german hungarian italian norwegian portuguese romanian russian spanish swedish turkish

Enable full-text search

MongoDB has enabled full-text retrieval by default since version 2.6. If you are using previous versions, you need to enable full-text retrieval using the following code:


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

Or use the command:


mongod --setParameter textSearchEnabled=true

Creating a full-text index

Consider the following posts collection of document data, including the article content (post_text) and the label (tags) :


{
  "post_text": "enjoy the mongodb articles on Runoob",
  "tags": [
   "mongodb",
   "runoob"
  ]
}

We can create a full-text index on the post_text field so that we can search for content within the article:


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

Using a full-text index

Now that we have a full-text index on post_text, we can search for the keyword runoob in the article:


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

The following command returns the following document data containing the runoob keyword:


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

If you are using an older version of MongoDB, you can use the following command:


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

Using full-text indexes can improve search efficiency.

Delete full-text index

To delete an existing full-text index, use the find command to find the index name:


>db.posts.getIndexes()

Get the index name from the above command. In this case, the index name is post_text_text.


>db.posts.dropIndex("post_text_text")

The above is the detailed analysis of MongoDB full text search, more information about MongoDB full text search, please pay attention to other relevant articles on this site!


Related articles: