MongoDB 全文检索
系统讲解 MongoDB 倒排全文索引原理、15 种内置分词语言、2.6+ 默认启用机制、text 索引创建与 $text/$search 检索及索引查询删除流程,并在离线倒排索引器中完成验证。
学完这一章,你能够
- 系统讲解 MongoDB 倒排全文索引原理、15 种内置分词语言、2.6+ 默认启用机制、text 索引创建与 $text/$search 检索及索引查询删除流程,并在离线倒排索引器中完成验证。
倒排全文检索原理、15 种内置语言与版本启用
全文检索(Text Search)通过对文本字段分词并建立倒排索引(记录每个词项出现的文档位置与词频),让查询像查字典检索表一样直接命中包含目标词的文档。MongoDB 自 2.4 版本起引入全文检索能力,内置 15 种支持词干提取与停用词过滤的开源语言:`danish`、`dutch`、`english`、`finnish`、`french`、`german`、`hungarian`、`italian`、`norwegian`、`portuguese`、`romanian`、`russian`、`spanish`、`swedish` 与 `turkish`(注意社区版内置全文索引不含中文分词,中文检索通常借助应用层分词或 Atlas Search/专用搜索引擎)。
自 MongoDB 2.6 起全文检索已默认开启,无需额外开关;仅在 2.4 等历史版本中才需要通过 `db.adminCommand({setParameter: true, textSearchEnabled: true})` 或启动参数 `mongod --setParameter textSearchEnabled=true` 手动启用。
创建、使用与删除全文索引
在包含 `post_text` 与 `tags` 字段的 `posts` 集合上,执行 `db.posts.createIndex({post_text: "text"})`(早期写法为 `ensureIndex`)即可为文本字段建立名为 `post_text_text` 的倒排全文索引(每个集合最多只能有一个 `text` 索引,但单个 `text` 索引可覆盖多个文本字段)。查询时使用标准 `$text` 操作符:`db.posts.find({$text: {$search: "devportal"}})`,它会自动执行大小写折叠与停用词过滤并高效返回匹配文档(2.4 时代旧命令 `db.posts.runCommand("text", {search: ...})` 已在 2.6+ 被 `$text` 查询操作符取代并移除)。
若需移除不再使用的全文索引,可先调用 `db.posts.getIndexes()`(注意源文本笔误写作 `find` 命令,实际列出集合全部索引名称的标准方法是 `getIndexes()`)查出目标索引名 `post_text_text`,再执行 `db.posts.dropIndex("post_text_text")` 将其删除。离线倒排索引脚本完整验证了 15 种语言列表、英文停用词过滤、关键词命中以及删除索引后拒绝 `$text` 查询的完整生命周期。
离线倒排全文索引验证 15 种语言配置、$text 停用词过滤与 dropIndex 生命周期
展开查看收起
"""Offline MongoDB full-text inverted index creation, $text search & dropIndex verifier."""
from collections import defaultdict
import json
import re
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
SUPPORTED_15_LANGUAGES = [
"danish", "dutch", "english", "finnish", "french",
"german", "hungarian", "italian", "norwegian", "portuguese",
"romanian", "russian", "spanish", "swedish", "turkish",
]
ENGLISH_STOP_WORDS = {"the", "on", "a", "an", "in", "of", "to", "for", "and", "is"}
class TextIndexStore:
def __init__(self):
self.docs = []
self.indexes = {"_id_": {"key": {"_id": 1}, "type": "btree"}}
self.inverted = defaultdict(set)
def insert(self, doc):
self.docs.append(dict(doc))
@staticmethod
def tokenize(text):
tokens = re.findall(r"[a-z0-9]+", text.lower())
return [t for t in tokens if t not in ENGLISH_STOP_WORDS]
def create_text_index(self, field):
idx_name = f"{field}_text"
self.indexes[idx_name] = {"key": {field: "text"}, "type": "text"}
self.inverted.clear()
for i, doc in enumerate(self.docs):
for tok in self.tokenize(str(doc.get(field, ""))):
self.inverted[tok].add(i)
return idx_name
def text_search(self, query):
if not any(meta["type"] == "text" for meta in self.indexes.values()):
raise RuntimeError("text index required for $text query")
terms = self.tokenize(query)
matched_ids = set()
for term in terms:
matched_ids.update(self.inverted.get(term, set()))
return [self.docs[i] for i in sorted(matched_ids)]
def drop_index(self, idx_name):
removed = self.indexes.pop(idx_name, None)
if removed and removed["type"] == "text":
self.inverted.clear()
return removed is not None
def main():
store = TextIndexStore()
store.insert({
"_id": "53493d14d852429c10000002",
"post_text": "enjoy the mongodb articles on DevPortal",
"tags": ["mongodb", "devportal"],
})
store.insert({
"_id": "53493d14d852429c10000003",
"post_text": "building scalable indexes in NoSQL databases",
"tags": ["nosql", "index"],
})
# Case 1: 15 supported languages & textSearchEnabled default in MongoDB 2.6+
c1_actual = {
"language_count": len(SUPPORTED_15_LANGUAGES),
"first_and_last_lang": [SUPPORTED_15_LANGUAGES[0], SUPPORTED_15_LANGUAGES[-1]],
"default_enabled_since": "2.6",
}
c1_expected = {
"language_count": 15,
"first_and_last_lang": ["danish", "turkish"],
"default_enabled_since": "2.6",
}
# Case 2: Create text index on post_text & case-insensitive inverted-index $text search
idx_name = store.create_text_index("post_text")
hits = store.text_search("devportal")
stopword_hits = store.text_search("the")
c2_actual = {
"created_index_name": idx_name,
"matched_ids": [d["_id"] for d in hits],
"stopword_only_hits": len(stopword_hits),
}
c2_expected = {
"created_index_name": "post_text_text",
"matched_ids": ["53493d14d852429c10000002"],
"stopword_only_hits": 0,
}
# Case 3: getIndexes() inspection and dropIndex("post_text_text")
before_drop = sorted(store.indexes.keys())
dropped = store.drop_index("post_text_text")
after_drop = sorted(store.indexes.keys())
try:
store.text_search("devportal")
error_after_drop = False
except RuntimeError:
error_after_drop = True
c3_actual = {
"indexes_before_drop": before_drop,
"dropped": dropped,
"indexes_after_drop": after_drop,
"search_blocked_after_drop": error_after_drop,
}
c3_expected = {
"indexes_before_drop": ["_id_", "post_text_text"],
"dropped": True,
"indexes_after_drop": ["_id_"],
"search_blocked_after_drop": True,
}
cases = [
{
"name": "text_search_languages_and_enablement",
"summary": "Verify 15 built-in full-text languages and default enablement since MongoDB 2.6.",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "create_text_index_and_search",
"summary": "Verify inverted text index creation on post_text, case-insensitive keyword matching, and stop-word filtering.",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "inspect_and_drop_text_index",
"summary": "Verify getIndexes() lists post_text_text and dropIndex() removes it so subsequent $text queries fail.",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
每个集合最多只能有一个 text 索引;但可以创建一个覆盖多个字段的复合全文索引,例如 db.posts.createIndex({title: 'text', body: 'text'})。