文本索引与全文检索
本教程共 50 篇 · 第 43 篇 · 更新于 2026-07-30 · 约 4 分钟阅读
43. 文本索引与全文检索
本节目标:会用文本索引做全文检索,理解权重与默认语言,并知道中文搜索的坑在哪。
前面讲的索引都做精确或范围匹配。要搜「内容里含某些词」的文档,得用文本索引(Text Index)。它支持对字符串内容做全文检索。
43.1 建立文本索引
用 "text" 作为索引类型即可。一个集合最多只能建一个文本索引,但可包含多个字段。
// 在 products 的 name 和 tags 上建文本索引
test> db.products.createIndex({ name: "text", tags: "text" })
插入示例商品:
test> db.products.insertMany([
{ _id: 1, name: "机械键盘", price: 399, category: "外设", tags: ["gamer", "rgb"], location: { type: "Point", coordinates: [120.15, 30.28] } },
{ _id: 2, name: "无线鼠标", price: 89, category: "外设", tags: ["office"], location: { type: "Point", coordinates: [120.16, 30.29] } },
{ _id: 3, name: "游戏耳机", price: 199, category: "外设", tags: ["gamer", "rgb"], location: { type: "Point", coordinates: [120.17, 30.27] } }
])
Warning一个集合只能有一个
text索引。想换字段组合,得先删掉旧的再建新的。
43.2 用 $text 做检索
全文检索靠 $text 操作符,配合 $search 指定关键词。多个词默认是「或」的关系。
// 搜包含 gamer 或 rgb 的商品
test> db.products.find({ $text: { $search: "gamer rgb" } })
加 - 前缀表示排除,加 \"" 双引号表示短语精确匹配:
// 含 gamer 但不含 office
test> db.products.find({ $text: { $search: "gamer -office" } })
43.3 相关性得分与排序
文本检索会给每个结果算一个相关性得分(Text Score)。用 $meta: "textScore" 取出来并排序:
// 返回得分,并按得分从高到低排
test> db.products.find(
{ $text: { $search: "gamer rgb" } },
{ name: 1, score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })
Tip想让「标题命中」比「标签命中」更重要?靠下面讲的 weights 调。
43.4 权重:让重要字段更靠前
weights 给不同字段分配重要性,默认都是 1。权重高的字段命中后得分更高。
// name 权重 10,tags 权重 3,标题命中排更前
test> db.products.createIndex(
{ name: "text", tags: "text" },
{ weights: { name: 10, tags: 3 }, name: "idx_text_products" }
)
43.5 默认语言
文本索引默认语言是 english,会用对应语言的分词和停用词(Stop Words)规则。可换成其它语言:
// 指定默认语言为 spanish
test> db.products.createIndex(
{ name: "text" },
{ default_language: "spanish" }
)
若设 default_language: "none",则不做任何语言处理,原样按词切分。
Warning中文没有可靠的分词规则。MongoDB 自管理的
$text对中文支持很弱(按空格/标点切,连写的中文难命中)。生产级中文搜索建议用 Atlas Search,或接 Elasticsearch 等外部方案。
43.6 关于 $search
顺带提一句:$search 是 MongoDB Atlas Search 的操作符,跑在专门的 Search 索引上,能力和中文分词都强很多。它与本章的 $text(自管理 text 索引)不是一回事。本地 8.3 部署请先用 $text;Atlas Search 是 Atlas 云服务的能力,自托管集群需额外部署 Search Node 才能用,别以为开箱即用。
43.7 小结
文本索引用 "text" 类型建,一集合仅一个,可多字段。$text + $search 做全文检索,$meta:"textScore" 排相关性。weights 调权重,default_language 设语言,中文场景要另寻方案。