您当前的位置: 首页 >  mongodb

小志的博客

暂无认证

  • 0浏览

    0关注

    1217博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

小志的博客 发布时间:2022-05-03 20:51:50 ,浏览量:0

目录
    • 一、MongoDB官网地址
    • 二、MongoDB全文索引(Text Indexes)的概述
    • 三、MongoDB创建全文索引(Text Indexes)的语法
    • 四、MongoDB创建全文索引(Text Indexes)的示例
      • 4.1、数据准备
      • 4.2、创建全文索引(Text Indexes)
      • 4.3、通过$text操作符查询数据

一、MongoDB官网地址
  • MongoDB官网地址:https://www.mongodb.com/docs/manual/core/index-single/
二、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"}})
    

    在这里插入图片描述

关注
打赏
1661269038
查看更多评论
立即登录/注册

微信扫码登录

0.0411s