课程表

MongoDB 基础教程

MongoDB 高级教程

工具箱
速查手册

MongoDB 全文检索

当前位置:免费教程 » 数据库/运维 » MongoDB

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

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

MongoDB 从 2.4 版本开始支持全文检索,目前支持15种语言(暂时不支持中文)的全文索引。

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

启用全文检索

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

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

或者使用命令:

  1. mongod --setParameter textSearchEnabled=true

创建全文索引

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

  1. {
  2. "post_text": "enjoy the mongodb articles on w3xue.com",
  3. "tags": [
  4. "mongodb",
  5. "w3cschool"
  6. ]
  7. }

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

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

使用全文索引

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

  1. >db.posts.find({$text:{$search:"w3xue.com"}})

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

  1. {
  2. "_id" : ObjectId("53493d14d852429c10000002"),
  3. "post_text" : "enjoy the mongodb articles on w3xue.com",
  4. "tags" : [ "mongodb", "w3cschool" ]
  5. }
  6. {
  7. "_id" : ObjectId("53493d1fd852429c10000003"),
  8. "post_text" : "writing tutorials on w3xue.com",
  9. "tags" : [ "mongodb", "tutorial" ]
  10. }

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

  1. >db.posts.runCommand("text",{search:" w3xue.com"})

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


删除全文索引

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

  1. >db.posts.getIndexes()

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

  1. >db.posts.dropIndex("post_text_text")
转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号