首页/数据/NoSQL 速查/文本索引与 $text 查询
本包目录(322 条)
MongoDB99 条
Elasticsearch89 条ClickHouse56 条时序与列式28 条选型与架构50 条

文本索引与 $text 查询

$text 查询依赖文本索引:支持词项、短语与排除词,配合 $meta: "textScore" 可按相关度排序。

NoSQL 速查数据更新于 2026-10-12
前提集合上已建文本索引
语法{ $text: { $search: "词 -排除词" } }
排序$meta: "textScore"

建索引并查询

建索引并查询
db.articles.createIndex({ title: "text", body: "text" }, { weights: { title: 10, body: 1 } })
db.articles.find({ $text: { $search: "分布式 事务 -mongodb" } }, { score: { $meta: "textScore" } }).sort({ score: { $meta: "textScore" } })
文本索引对中文按空格与标点切词,中文检索效果有限;整句分词需求应评估外部检索方案。

易错点

  • 每个集合只允许一个文本索引,多字段要合并建立
  • $text 必须作为顶层条件,不能嵌套在 $or 等子表达式内部使用

数据来源与参考

  • MongoDB Manual: $text
​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌