Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
45 lines
1.3 KiB
Python
45 lines
1.3 KiB
Python
"""Hash indexes for equality lookups."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any, Dict, Iterable, List, Mapping, Set
|
|
|
|
|
|
class HashIndex:
|
|
"""Maps the values of one column to the ids of the rows holding them.
|
|
|
|
NULL values are not indexed: ``lookup(None)`` is always empty.
|
|
"""
|
|
|
|
def __init__(self, column: str) -> None:
|
|
self.column = column
|
|
self._ids: Dict[Any, Set[int]] = {}
|
|
|
|
def add(self, row: Mapping[str, Any]) -> None:
|
|
value = row[self.column]
|
|
if value is not None:
|
|
self._ids.setdefault(value, set()).add(row["id"])
|
|
|
|
def remove(self, row: Mapping[str, Any]) -> None:
|
|
value = row[self.column]
|
|
if value is None:
|
|
return
|
|
bucket = self._ids.get(value)
|
|
if bucket is None:
|
|
return
|
|
bucket.discard(row["id"])
|
|
if not bucket:
|
|
del self._ids[value]
|
|
|
|
def lookup(self, value: Any) -> List[int]:
|
|
"""Ids of the rows whose column equals ``value``, in ascending order."""
|
|
return sorted(self._ids.get(value, ()))
|
|
|
|
def rebuild(self, rows: Iterable[Mapping[str, Any]]) -> None:
|
|
self._ids.clear()
|
|
for row in rows:
|
|
self.add(row)
|
|
|
|
def __len__(self) -> int:
|
|
return sum(len(bucket) for bucket in self._ids.values())
|