MongoDB 文本搜索

从2.4版本开始,MongoDB 开始支持文本索引来搜索字符串内容。Text Search(文本搜索) 使用词干分析技术在字符串字段中通过删除词干分析停止词(如 a、 an、 The 等)来查找指定的词。目前,MongoDB 支持大约15种语言。

启用文本搜索

最初,“Text Search(文本搜索)”是一项实验性功能,但从2.6版开始,默认情况下启用此配置。

创建文本索引

考虑以下posts集合中的文档,其中包含帖子文本及其标签-

> db.posts.insert({
   "post_text": "enjoy the mongodb articles on nhooo",
   "tags": ["mongodb", "nhooo"]
}
{
	"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字段上创建了文本索引,我们将搜索nhooo文本中包含单词的所有帖子。

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

上面的命令返回以下结果文档,该结果文档nhooo的发布文本中包含单词:

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

删除文本索引

要删除现有的文本索引,请首先使用以下查询找到索引的名称-

>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 }