MongoDB 從 2.4 版本起就開始支持全文索引,以便搜索字符串內(nèi)容。文本搜索使用字干搜索技術(shù)查找字符串字段中的指定詞語,丟棄字干停止詞(比如 a、an、the等)。迄今為止,MongoDB 支持大約 15 種語言。
最初的文本搜索只是一種試驗(yàn)性功能,但從 2.6 版本起就成為默認(rèn)功能了。但如果使用的是之前的 MongoDB,則需要使用下列代碼啟用文本搜索:
>db.adminCommand({setParameter:true,textSearchEnabled:true})
假設(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")