MongoDB 全文检索

MongoDB 全文检索

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

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

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

danish

dutch

english

finnish

french

german

hungarian

italian

norwegian

portuguese

romanian

russian

spanish

swedish

turkish

启用全文检索

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

bash 复制代码
>db.adminCommand({setParameter:true,textSearchEnabled:true})

或者使用命令:

bash 复制代码
mongod --setParameter textSearchEnabled=true

创建全文索引

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

bash 复制代码
{
   "post_text": "enjoy the mongodb articles on Caiyuan",
   "tags": [
      "mongodb",
      "caiyuan"
   ]
}

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

bash 复制代码
>db.posts.ensureIndex({post_text:"text"})

使用全文索引

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

bash 复制代码
>db.posts.find({$text:{$search:"caiyuan"}})

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

bash 复制代码
{ 
   "_id" : ObjectId("53493d14d852429c10000009"), 
   "post_text" : "enjoy the mongodb articles on Caiyuan", 
   "tags" : [ "mongodb", "caiyuan" ]
}

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

bash 复制代码
>db.posts.runCommand("text",{search:"caiyuan"})

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

删除全文索引

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

bash 复制代码
>db.posts.getIndexes()

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

bash 复制代码
>db.posts.dropIndex("post_text_text")
相关推荐
ClouGence7 小时前
MongoDB 双向同步如何防止数据循环?(附实操指南)
数据库·mongodb
Elastic 中国社区官方博客8 小时前
AgentHack Shanghai|基于阿里云AI搜索 Elasticsearch x Qoder 构建AI Agent应用
大数据·人工智能·elasticsearch·搜索引擎·阿里云·云计算·全文检索
实名上网宋凯宣18 小时前
Django
后端·python·django
汤米粥1 天前
cmd手动创建的Django项目怎么用社区版Pycharm运行起来
python·pycharm·django
码农阿豪1 天前
MongoDB迁移到金仓数据库:商品属性继续灵活存,订单报表交给 SQL
数据库·sql·mongodb
todoitbo2 天前
MongoDB迁移之后,Spring Data 和 Hibernate 各自接哪类请求
大数据·数据库·mongodb·spring·hibernate·金仓数据库
Rambo.Fan2 天前
02 · 重建与修复手册(新服务器 playbook)
运维·服务器·django
雨晨源码(同名B站)2 天前
深度学习毕业设计选题推荐:基于YOLO11的交通标志检测系统设计与实现(Python+Django+Vue3+对接deepseek)
人工智能·python·深度学习·机器学习·django·课程设计
云边有个稻草人2 天前
MongoDB迁移不止是数据搬家:用KingbaseES重构文档数据开发
数据库·mongodb·重构·国产数据库·信创数据库·数据库国产化·mongodb迁移
言乐64 天前
通过 3D 动画直观演示球形瓶内可滑动半圆机构在倾倒时防粘盖、回正时刮膏体的运动学过程
python·3d·django·virtualenv·pygame