鍍金池/ 教程/ 數(shù)據(jù)庫/ 全文檢索
更新文檔
GridFS
Rockmongo 管理工具
Map Reduce
Java
創(chuàng)建備份
數(shù)據(jù)模型
創(chuàng)建數(shù)據(jù)庫
映射
查詢文檔
索引限制
ObjectId
刪除文檔
數(shù)據(jù)類型
高級索引
索引
優(yōu)勢
記錄排序
查詢分析
插入文檔
刪除集合
全文檢索
創(chuàng)建集合
概述
數(shù)據(jù)庫引用
覆蓋索引查詢
安裝環(huán)境
PHP
刪除數(shù)據(jù)庫
固定集合
關(guān)系
聚合
自動增長
復(fù)制
限制記錄
部署
分片
正則表達(dá)式
原子操作

全文檢索

MongoDB 從 2.4 版本起就開始支持全文索引,以便搜索字符串內(nèi)容。文本搜索使用字干搜索技術(shù)查找字符串字段中的指定詞語,丟棄字干停止詞(比如 a、an、the等)。迄今為止,MongoDB 支持大約 15 種語言。

啟用文本搜索

最初的文本搜索只是一種試驗(yàn)性功能,但從 2.6 版本起就成為默認(rèn)功能了。但如果使用的是之前的 MongoDB,則需要使用下列代碼啟用文本搜索:

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

創(chuàng)建文本索引

假設(shè)在 posts 集合中的下列文檔中含有帖子文本及其標(biāo)簽。

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

我們將在 post_text 字段上創(chuàng)建文本索引,以便搜索帖子文本之內(nèi)的內(nèi)容。

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

使用文本索引

現(xiàn)在我們已經(jīng)在 post_text 字段上創(chuàng)建了文本索引,接下來搜索包含 tutorialspoint 文本內(nèi)容的帖子。

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

在返回的結(jié)果文檔中,果然包含了具有 tutorialspoint 文本的帖子文本。

{ 
   "_id" : ObjectId("53493d14d852429c10000002"), 
   "post_text" : "enjoy the mongodb articles on tutorialspoint", 
   "tags" : [ "mongodb", "tutorialspoint" ]
}
{
   "_id" : ObjectId("53493d1fd852429c10000003"), 
   "post_text" : "writing tutorials on mongodb",
   "tags" : [ "mongodb", "tutorial" ] 
}

如果用的是舊版本的 MongoDB,則需使用下列代碼:

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

總之,與普通搜索相比,使用文本搜索可極大地改善搜索效率。

刪除文本索引

要想刪除已有的文本索引,首先要找到索引名稱:

>db.posts.getIndexes()

從上述查詢中獲取了索引名稱后,運(yùn)行下列命令,post_text_text 是我們需要刪掉的索引名稱。

>db.posts.dropIndex("post_text_text")

上一篇:復(fù)制下一篇:部署