蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线倒排全文索引验证 15 种语言配置、$text 停用词过滤与 dropIndex 生命周期

PYTHONWindows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。explore-text-search.py
explore-text-search.py145 行
"""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()
本例需在 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。

入口文件:projects/mongodb-text-search-lab/explore-text-search.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-text-search.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:MongoDB

课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip

下载课程关联工程包:MongoDB

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1772.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习