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

运行 B-tree 索引查找、unique+sparse 约束、TTL 过期淘汰、文本/地理/哈希索引及写入放大验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-indexing.py
explore-indexing.py264 行
"""Offline MongoDB B-tree, compound, unique, sparse, TTL, text/geo/hashed index verifier (Ch24 indexing)."""
import bisect
import datetime
import hashlib
import json
import math

VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"


class OfflineIndexedCollection:
    def __init__(self):
        self.docs = []
        self.indexes = {
            "_id_": {"keys": [("_id", 1)], "unique": True, "sparse": False, "entries": []},
        }
        self.index_write_ops = 0

    @staticmethod
    def auto_name(keys: list[tuple[str, int | str]]) -> str:
        return "_".join(f"{k}_{v}" for k, v in keys)

    def create_index(self, keys: list[tuple[str, int | str]], unique=False, sparse=False, name=None, expire_after_seconds=None, weights=None):
        idx_name = name or self.auto_name(keys)
        meta = {
            "keys": list(keys),
            "unique": unique,
            "sparse": sparse,
            "expireAfterSeconds": expire_after_seconds,
            "weights": weights,
            "entries": [],
        }
        for pos, d in enumerate(self.docs):
            self._index_doc(meta, d, pos)
        self.indexes[idx_name] = meta
        return idx_name

    def _index_doc(self, meta: dict, doc: dict, pos: int):
        fields = [k for k, _ in meta["keys"]]
        if meta["sparse"] and not any(f in doc for f in fields):
            return
        key_tuple = tuple(doc.get(f) for f in fields)
        if meta["unique"]:
            existing_keys = [k for k, _ in meta["entries"]]
            if key_tuple in existing_keys:
                raise ValueError(f"E11000 duplicate key: {key_tuple}")
        bisect.insort(meta["entries"], (key_tuple, pos))
        self.index_write_ops += 1

    def insert_one(self, doc: dict):
        pos = len(self.docs)
        # Validate unique indexes before committing
        for meta in self.indexes.values():
            fields = [k for k, _ in meta["keys"]]
            if meta["sparse"] and not any(f in doc for f in fields):
                continue
            key_tuple = tuple(doc.get(f) for f in fields)
            if meta["unique"] and any(k == key_tuple for k, _ in meta["entries"]):
                raise ValueError(f"E11000 duplicate key: {key_tuple}")
        self.docs.append(dict(doc))
        for meta in self.indexes.values():
            self._index_doc(meta, doc, pos)

    def get_indexes(self) -> list[str]:
        return sorted(self.indexes.keys())

    def drop_index(self, idx_name: str):
        if idx_name == "_id_":
            raise ValueError("cannot drop _id index")
        return self.indexes.pop(idx_name, None) is not None

    def drop_indexes(self):
        for k in list(self.indexes.keys()):
            if k != "_id_":
                del self.indexes[k]


def case_single_and_compound_btree_index_lookup():
    col = OfflineIndexedCollection()
    for i in range(1, 51):
        col.insert_one({"_id": i, "age": 18 + (i % 40), "dept": "eng" if i % 2 == 0 else "ops"})
    col.create_index([("age", 1)])
    col.create_index([("dept", 1), ("age", -1)])

    # Full scan examines all 50 docs; B-tree bisect on age==57 examines only matching entries
    collscan_examined = len(col.docs)
    entries = col.indexes["age_1"]["entries"]
    target = (57,)
    lo = bisect.bisect_left(entries, (target, -1))
    hi = bisect.bisect_right(entries, (target, 10**9))
    ixscan_hits = [col.docs[pos]["_id"] for _, pos in entries[lo:hi]]

    # Compound prefix rule for ("dept", "age")
    compound_fields = [k for k, _ in col.indexes["dept_1_age_-1"]["keys"]]
    supports_dept = compound_fields[:1] == ["dept"]
    supports_dept_age = compound_fields[:2] == ["dept", "age"]
    supports_age_only = compound_fields[:1] == ["age"]

    actual = {
        "collscan_examined": collscan_examined,
        "ixscan_examined": len(ixscan_hits),
        "ixscan_ids": ixscan_hits,
        "compound_prefix_checks": [supports_dept, supports_dept_age, supports_age_only],
    }
    expected = {
        "collscan_examined": 50,
        "ixscan_examined": 1,
        "ixscan_ids": [39],
        "compound_prefix_checks": [True, True, False],
    }
    return {
        "name": "single_and_compound_btree_index_lookup",
        "summary": "对比全集合扫描(50 文档)与 B-tree 索引二分查找(1 文档),并验证复合索引最左前缀规则。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_unique_and_sparse_index_constraints():
    col = OfflineIndexedCollection()
    col.create_index([("email", 1)], unique=True, sparse=True)
    col.insert_one({"_id": 1, "email": "alice@example.com"})
    # Sparse unique index allows multiple docs missing the email field!
    col.insert_one({"_id": 2, "name": "no_email_1"})
    col.insert_one({"_id": 3, "name": "no_email_2"})
    dup_rejected = False
    try:
        col.insert_one({"_id": 4, "email": "alice@example.com"})
    except ValueError:
        dup_rejected = True

    actual = {
        "indexed_entries_count": len(col.indexes["email_1"]["entries"]),
        "total_docs_stored": len(col.docs),
        "duplicate_email_rejected": dup_rejected,
    }
    expected = {
        "indexed_entries_count": 1,
        "total_docs_stored": 3,
        "duplicate_email_rejected": True,
    }
    return {
        "name": "unique_and_sparse_index_constraints",
        "summary": "验证 unique + sparse 索引拒绝重复 email,同时跳过缺失该字段的文档。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_ttl_expire_after_seconds_eviction():
    now = datetime.datetime(2026, 6, 1, 12, 0, 0, tzinfo=datetime.timezone.utc)
    ttl_seconds = 3600
    sessions = [
        {"_id": "s1", "createdAt": datetime.datetime(2026, 6, 1, 10, 0, 0, tzinfo=datetime.timezone.utc)},
        {"_id": "s2", "createdAt": datetime.datetime(2026, 6, 1, 11, 30, 0, tzinfo=datetime.timezone.utc)},
        {"_id": "s3", "createdAt": datetime.datetime(2026, 6, 1, 11, 55, 0, tzinfo=datetime.timezone.utc)},
    ]
    surviving = [
        s["_id"]
        for s in sessions
        if (now - s["createdAt"]).total_seconds() < ttl_seconds
    ]
    expected = ["s2", "s3"]
    return {
        "name": "ttl_expire_after_seconds_eviction",
        "summary": "验证 expireAfterSeconds: 3600 TTL 索引自动清理超时会话并保留有效文档。",
        "expected": expected,
        "actual": surviving,
        "passed": surviving == expected,
    }


def case_text_weights_geo_and_hashed_indexes():
    # Weighted text scoring: title weight 10 vs body weight 1
    docs = [
        {"id": 1, "title": "MongoDB Indexing", "body": "guide"},
        {"id": 2, "title": "Database Guide", "body": "indexing tips for indexing speed"},
    ]
    weights = {"title": 10, "body": 1}
    scores = {}
    for d in docs:
        s = sum(d[f].lower().split().count("indexing") * w for f, w in weights.items())
        scores[d["id"]] = s
    ranked = sorted(scores, key=lambda i: scores[i], reverse=True)

    # 2d planar distance & hashed bucket
    pts = [("p1", (0.0, 0.0)), ("p2", (3.0, 4.0)), ("p3", (10.0, 10.0))]
    within_6 = [pid for pid, (x, y) in pts if math.hypot(x, y) <= 6.0]
    h_bucket = int(hashlib.md5(b"shard_key_42").hexdigest(), 16) % 4

    actual = {
        "weighted_text_rank": ranked,
        "scores": scores,
        "geo_2d_within_6": within_6,
        "hashed_bucket_in_range": 0 <= h_bucket < 4,
    }
    expected = {
        "weighted_text_rank": [1, 2],
        "scores": {1: 10, 2: 2},
        "geo_2d_within_6": ["p1", "p2"],
        "hashed_bucket_in_range": True,
    }
    return {
        "name": "text_weights_geo_and_hashed_indexes",
        "summary": "验证文本索引 weights 权重排序、2d 平面距离筛选与 hashed 索引分桶分布。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_index_management_get_drop_and_write_overhead():
    col = OfflineIndexedCollection()
    n1 = col.create_index([("age", 1)])
    n2 = col.create_index([("name", "text")], name="name_text_custom")
    before = col.get_indexes()
    col.index_write_ops = 0
    col.insert_one({"_id": 1, "age": 25, "name": "Alice"})
    writes_with_3_indexes = col.index_write_ops
    col.drop_index(n1)
    after_drop_one = col.get_indexes()
    col.drop_indexes()
    after_drop_all = col.get_indexes()
    actual = {
        "auto_name": n1,
        "custom_name": n2,
        "before_drop": before,
        "writes_per_insert_with_3_indexes": writes_with_3_indexes,
        "after_drop_age": after_drop_one,
        "after_drop_all_keeps_id": after_drop_all,
    }
    expected = {
        "auto_name": "age_1",
        "custom_name": "name_text_custom",
        "before_drop": ["_id_", "age_1", "name_text_custom"],
        "writes_per_insert_with_3_indexes": 3,
        "after_drop_age": ["_id_", "name_text_custom"],
        "after_drop_all_keeps_id": ["_id_"],
    }
    return {
        "name": "index_management_get_drop_and_write_overhead",
        "summary": "验证 createIndex 自动命名、getIndexes、dropIndex/dropIndexes(保留 _id_)及索引写入放大开销。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_single_and_compound_btree_index_lookup(),
        case_unique_and_sparse_index_constraints(),
        case_ttl_expire_after_seconds_eviction(),
        case_text_weights_geo_and_hashed_indexes(),
        case_index_management_get_drop_and_write_overhead(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

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

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-indexing.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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