MongoDB - 文字搜尋



從 2.4 版本開始,MongoDB 開始支援文字索引以搜尋字串內容。文字搜尋使用詞幹提取技術,透過刪除諸如a、an、the等詞幹停止詞來查詢字串欄位中的指定單詞。目前,MongoDB 支援約 15 種語言。

啟用文字搜尋

最初,文字搜尋是一個實驗性功能,但從 2.6 版本開始,預設情況下啟用該配置。

建立文字索引

考慮一下posts集合下包含帖子文字及其標籤的以下文件:

> db.posts.insert({
   "post_text": "enjoy the mongodb articles on tutorialspoint",
   "tags": ["mongodb", "tutorialspoint"]
}
{
	"post_text" : "writing tutorials on mongodb",
	"tags" : [ "mongodb", "tutorial" ]
})
WriteResult({ "nInserted" : 1 })

我們將在 post_text 欄位上建立一個文字索引,以便我們可以在帖子的文字中進行搜尋:

>db.posts.createIndex({post_text:"text"})
{
	"createdCollectionAutomatically" : true,
	"numIndexesBefore" : 1,
	"numIndexesAfter" : 2,
	"ok" : 1
}

使用文字索引

現在我們在 post_text 欄位上建立了文字索引,我們將搜尋所有在其文字中包含單詞tutorialspoint的帖子。

> db.posts.find({$text:{$search:"tutorialspoint"}}).pretty()
{
	"_id" : ObjectId("5dd7ce28f1dd4583e7103fe0"),
	"post_text" : "enjoy the mongodb articles on tutorialspoint",
	"tags" : [
		"mongodb",
		"tutorialspoint"
	]
}

上述命令返回了在其帖子文字中包含單詞tutorialspoint的以下結果文件:

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

刪除文字索引

要刪除現有文字索引,首先使用以下查詢查詢索引的名稱:

>db.posts.getIndexes()
[
	{
		"v" : 2,
		"key" : {
			"_id" : 1
		},
		"name" : "_id_",
		"ns" : "mydb.posts"
	},
	{
		"v" : 2,
		"key" : {
			"fts" : "text",
			"ftsx" : 1
		},
		"name" : "post_text_text",
		"ns" : "mydb.posts",
		"weights" : {
			"post_text" : 1
		},
		"default_language" : "english",
		"language_override" : "language",
		"textIndexVersion" : 3
	}
]
>

從上面的查詢中獲取索引的名稱後,執行以下命令。這裡,post_text_text是索引的名稱。

>db.posts.dropIndex("post_text_text")
{ "nIndexesWas" : 2, "ok" : 1 }
廣告