MongoDB 全文检索

MongoDB 教程 · 2019-03-06 09:57:54

全文检索对每一个词建立一个索引,指明该词在文章中出现的次数和位置,当用户查询时,检索程序就根据事先建立的索引进行查找,并将查找的结果反馈给用户的检索方式。

这个过程类似于通过字典中的检索字表查字的过程。

MongoDB 从 2.4 版本开始支持全文检索,目前支持15种语言的全文索引。

  • danish
  • dutch
  • english
  • finnish
  • french
  • german
  • hungarian
  • italian
  • norwegian
  • portuguese
  • romanian
  • russian
  • spanish
  • swedish
  • turkish

启用全文检索

MongoDB 在 2.6 版本以后是默认开启全文检索的,如果你使用之前的版本,你需要使用以下代码来启用全文检索:

>db.adminCommand({setParameter:true,textSearchEnabled:true})

或者使用命令:

mongod --setParameter textSearchEnabled=true

创建全文索引

考虑以下 posts 集合的文档数据,包含了文章内容(post_text)及标签(tags):

{
   "post_text": "enjoy the mongodb articles on Codercto",
   "tags": [
      "mongodb",
      "codercto"
   ]
}

我们可以对 post_text 字段建立全文索引,这样我们可以搜索文章内的内容:

>db.posts.ensureIndex({post_text:"text"})

使用全文索引

现在我们已经对 post_text 建立了全文索引,我们可以搜索文章中的关键词 codercto:

>db.posts.find({$text:{$search:"codercto"}})

以下命令返回了如下包含 codercto 关键词的文档数据:

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

如果你使用的是旧版本的 MongoDB,你可以使用以下命令:

>db.posts.runCommand("text",{search:"codercto"})

使用全文索引可以提高搜索效率。

删除全文索引

删除已存在的全文索引,可以使用 find 命令查找索引名:

>db.posts.getIndexes()

通过以上命令获取索引名,本例的索引名为post_text_text,执行以下命令来删除索引:

>db.posts.dropIndex("post_text_text")

点击查看所有 MongoDB 教程 文章: https://codercto.com/courses/l/32.html

标签: 全文检索

Computers and Intractability

Computers and Intractability

M R Garey、D S Johnson / W. H. Freeman / 1979-4-26 / GBP 53.99

This book's introduction features a humorous story of a man with a line of people behind him, who explains to his boss, "I can't find an efficient algorithm, but neither can all these famous people." ......一起来看看 《Computers and Intractability》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

SHA 加密
SHA 加密

SHA 加密工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具