MongoDB 全文检索
MongoDB 全文检索
从2.4版开始,MongoDB开始支持全文检索以搜索字符串内容。文本搜索使用词干技术,通过丢弃词干停止词(如a, an, the等)来查找字符串字段中的指定单词。目前,MongoDB支持大约15种语言。
启用全文检索
最初,全文检索是一项实验功能,但从2.6版开始,默认情况下启用配置。但是,如果使用的是以前版本的MongoDB,则必须使用以下代码启用文本搜索-
>db.adminCommand({setParameter:true,textSearchEnabled:true})创建文本索引
假设posts集合包含以下内容:
{
"post_text": "enjoy the mongodb articles on tutorialspoint",
"tags": [
"mongodb",
"tutorialspoint"
]
}我们将在post_text字段上创建一个文本索引,以便可以在帖子的文本中搜索
>db.posts.ensureIndex({post_text:"text"})使用文本索引
现在我们已经在post_text字段上创建了文本索引,我们将搜索在其文本中具有单词tutorialspoint的所有帖子。
>db.posts.find({$text:{$search:"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()
从上述查询中获取索引名称后,运行以下命令。这里,post_text_text是索引的名称。
>db.posts.dropIndex("post_text_text")