MongoDB文本搜索


从2.4版本开始,MongoDB开始支持文本索引来搜索字符串内容内部。文本搜索使用词干技术,通过像a、an、the等词干的停顿词来寻找字符串字段中的指定单词。目前,MongoDB支持大约15种语言。

启用文本搜索


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

创建文本索引


考虑以下文件posts包含帖子文本及其标签的集合:

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

我们将在post_text字段上创建一个文本索引,以便我们可以在帖子的文本中进行搜索:

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

使用文本索引


现在,我们在post_text字段上创建了文本索引,我们将搜索所有包含单词的帖子newbiego在他们的文字中。

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

上面的命令返回了以下具有单词的结果文档newbiego在他们的帖子中:

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

删除文本索引


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

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