- MongoDB 教程
- MongoDB - 首页
- MongoDB - 概述
- MongoDB - 优势
- MongoDB - 环境
- MongoDB - 数据建模
- MongoDB - 创建数据库
- MongoDB - 删除数据库
- MongoDB - 创建集合
- MongoDB - 删除集合
- MongoDB - 数据类型
- MongoDB - 插入文档
- MongoDB - 查询文档
- MongoDB - 更新文档
- MongoDB - 删除文档
- MongoDB - 投影
- MongoDB - 限制记录
- MongoDB - 排序记录
- MongoDB - 索引
- MongoDB - 聚合
- MongoDB - 复制
- MongoDB - 分片
- MongoDB - 创建备份
- MongoDB - 部署
- MongoDB - Java
- MongoDB - PHP
- 高级 MongoDB
- MongoDB - 关系
- MongoDB - 数据库引用
- MongoDB - 覆盖查询
- MongoDB - 分析查询
- MongoDB - 原子操作
- MongoDB - 高级索引
- MongoDB - 索引限制
- MongoDB - ObjectId
- MongoDB - MapReduce
- MongoDB - 文本搜索
- MongoDB - 正则表达式
- 使用 Rockmongo
- MongoDB - GridFS
- MongoDB - 封顶集合
- 自动递增序列
- MongoDB 有用资源
- MongoDB - 常见问题解答
- MongoDB - 快速指南
- MongoDB - 有用资源
- MongoDB - 讨论
MongoDB - 文本搜索
从 2.4 版本开始,MongoDB 开始支持文本索引以搜索字符串内容。文本搜索使用词干提取技术,通过删除诸如a、an、the等词干停止词来查找字符串字段中的指定单词。目前,MongoDB 支持约 15 种语言。
启用文本搜索
最初,文本搜索是一个实验性功能,但从 2.6 版本开始,默认情况下启用该配置。
创建文本索引
考虑一下posts集合下包含帖子文本及其标签的以下文档:
> db.posts.insert({
"post_text": "enjoy the mongodb articles on tutorialspoint",
"tags": ["mongodb", "tutorialspoint"]
}
{
"post_text" : "writing tutorials on mongodb",
"tags" : [ "mongodb", "tutorial" ]
})
WriteResult({ "nInserted" : 1 })
我们将在 post_text 字段上创建一个文本索引,以便我们可以在帖子的文本中进行搜索:
>db.posts.createIndex({post_text:"text"})
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
使用文本索引
现在我们在 post_text 字段上创建了文本索引,我们将搜索所有在其文本中包含单词tutorialspoint的帖子。
> db.posts.find({$text:{$search:"tutorialspoint"}}).pretty()
{
"_id" : ObjectId("5dd7ce28f1dd4583e7103fe0"),
"post_text" : "enjoy the mongodb articles on tutorialspoint",
"tags" : [
"mongodb",
"tutorialspoint"
]
}
上述命令返回了在其帖子文本中包含单词tutorialspoint的以下结果文档:
{
"_id" : ObjectId("53493d14d852429c10000002"),
"post_text" : "enjoy the mongodb articles on tutorialspoint",
"tags" : [ "mongodb", "tutorialspoint" ]
}
删除文本索引
要删除现有文本索引,首先使用以下查询查找索引的名称:
>db.posts.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "mydb.posts"
},
{
"v" : 2,
"key" : {
"fts" : "text",
"ftsx" : 1
},
"name" : "post_text_text",
"ns" : "mydb.posts",
"weights" : {
"post_text" : 1
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 3
}
]
>
从上面的查询中获取索引的名称后,运行以下命令。这里,post_text_text是索引的名称。
>db.posts.dropIndex("post_text_text")
{ "nIndexesWas" : 2, "ok" : 1 }
广告