MongoDB——索引类型之全文索引(Text Indexes)

x33g5p2x  于2022-05-05 转载在 其他  
字(1.2k)|赞(0)|评价(0)|浏览(520)

一、MongoDB官网地址

二、MongoDB全文索引(Text Indexes)的概述

  • MongoDB支持全文检索功能,可通过建立文本索引来实现简易的分词检索。
  • 全文索引能解决快速文本查找的需求,比如有一个博客文章集合,需要根据博客的内容来快速查找,则可以针对博客内容建立文本索引。
  • MongoDB的文本索引功能存在诸多限制,而官方并未提供中文分词的功能,这使得该功能的应用场景十分受限。

三、MongoDB创建全文索引(Text Indexes)的语法

  • 语法
db.reviews.createIndex( { comments: "text" } )
  • 语法解释
操作符解释
$text在有text index的集合上执行文本检索。$text将会使用空格和标点符号作为分隔符对检索字符串进行分词, 并且对检索字符串中所有的分词结果进行一个逻辑上的 OR 操作。

四、MongoDB创建全文索引(Text Indexes)的示例

4.1、数据准备

  • 准备数据集,执行脚本
db.stores.insert(
 [
  { _id: 1, name: "Java Hut", description: "Coffee and cakes" },
  { _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },
  { _id: 3, name: "Coffee Shop", description: "Just coffee" },
  { _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing"},
  { _id: 5, name: "Java Shopping", description: "Indonesian goods" }
 ]
)

  • 查看初始化的数据
> db.stores.find()

4.2、创建全文索引(Text Indexes)

  • 创建name和description的全文索引
db.stores.createIndex({name: "text", description: "text"})

  • 查看创建的全文索引
> db.stores.getIndexes()

4.3、通过$text操作符查询数据

  • 通过$text操作符来查寻stores集合中所有包含“coffee”、”shop”、“java”的数据
> db.stores.find({$text: {$search: "java coffee shop"}})

相关文章