新聞中心

目前,MongoDB 支持大約 15 種語(yǔ)言的全文索引,例如 danish、dutch、english、finnish、french、german、hungarian、italian、norwegian、portuguese、romanian、russian、spanish、swedish、turkish 等。
啟用全文檢索
最初,全文檢索是一個(gè)實(shí)驗(yàn)性功能,但 MongoDB 在 2.6 版本以后默認(rèn)開啟了此功能,如果您使用 2.6 之前的版本,則需要使用以下代碼來(lái)啟用全文檢索:
>db.adminCommand({setParameter:true, textSearchEnabled:true})
或者使用命令:
mongod --setParameter textSearchEnabled=true
創(chuàng)建全文索引
假如我們?cè)?posts 集合中插入以下文檔:
> db.posts.insert([
... {
... "post_text": "enjoy the mongodb articles on bianchengbang",
... "tags": ["mongodb", "bianchengbang"]
... },
... {
... "post_text" : "writing tutorials on mongodb",
... "tags" : [ "mongodb", "tutorial" ]
... }
... ])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
若要在 post_text 字段上創(chuàng)建全文索引,以便我們可以直接搜索字段中的內(nèi)容,可以像下面這樣:
> db.posts.createIndex({post_text:"text"})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
使用全文索引
使用全文索引可以提高搜索效率,前面我們已經(jīng)在 post_text 字段上創(chuàng)建了全文索引,下面通過(guò)一個(gè)示例來(lái)演示全文索引的使用。
【示例】搜索 post_text 字段中包含關(guān)鍵詞“bianchengbang”的所有文檔:
> db.posts.find({$text:{$search:"bianchengbang"}}).pretty()
{
"_id" : ObjectId("6041dfc3835e4aa734b591df"),
"post_text" : "enjoy the mongodb articles on bianchengbang",
"tags" : [
"mongodb",
"bianchengbang"
]
}
如果您使用的是舊版本的 MongoDB,則可以使用以下命令:
>db.posts.runCommand("text",{search:"bianchengbang"})
刪除全文索引
要?jiǎng)h除現(xiàn)有的全文索引,首先我們需要使用 getIndex() 方法來(lái)查看索引的名稱,如下所示:
> db.posts.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "bianchengbang.posts"
},
{
"v" : 2,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"name" : "post_text_text",
"ns" : "bianchengbang.posts",
"weights" : {
"post_text" : 1
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 3
}
]
通過(guò)運(yùn)行結(jié)果可以看出,我們前面創(chuàng)建的索引的名稱為“post_text_text”,接下來(lái)就可以使用 dropIndex() 方法來(lái)刪除指定的索引了,如下所示:
> db.posts.dropIndex("post_text_text")
{ "nIndexesWas" : 2, "ok" : 1 }分享文章:MongoDB全文檢索
URL分享:http://www.dlmjj.cn/article/codsphj.html


咨詢
建站咨詢
