Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Build the systems
EXPERIMENT 66 / 66

Find the right document, not every word.

Combine hashing and set intersections into a practical AND-query engine.

BY NAVAN SAMI◷ 11 MIN READSTRETCHPROJECT

01 Model the idea

An inverted index maps a term to the documents containing it. A multi-term AND query intersects those posting sets instead of scanning every document again. Tokenisation and normalisation define what counts as the same term, so indexing and querying must use the same policy. This project deliberately uses a simple ASCII-letter policy rather than claiming full language-aware search.

THE THING THAT MUST STAY TRUE

Each posting set contains exactly the indexed documents that include the normalised term.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
TOKENISE every document
MAP each unique term to document ids
INTERSECT query-term postings
SORT matched ids for display

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

search_index.py
import re
def tokens(text): return re.findall(r"[a-z]+", text.casefold())
def build_index(documents):
    index = {}
    for identity, text in documents.items():
        for token in set(tokens(text)):
            index.setdefault(token, set()).add(identity)
    return index
def search(index, query):
    terms = set(tokens(query))
    if not terms: return []
    postings = [index.get(term, set()) for term in terms]
    postings.sort(key=len)
    result = set(postings[0])
    for posting in postings[1:]: result.intersection_update(posting)
    return sorted(result)
documents = {1: "Code builds systems", 2: "Systems need tests", 3: "Code and tests"}
index = build_index(documents)
print(search(index, "CODE tests"))
print(search(index, "unknown"))
↳ EXPECTED OUTPUT
[3]
[]
  1. 1

    Each document contributes its identity once per distinct token. Term frequency and positions are intentionally not stored.

  2. 2

    Starting from the shortest posting set can reduce intersection work. Sorting the final ids gives deterministic output rather than relying on set order.

  3. 3

    The empty-query policy returns no results. Real systems need explicit decisions about Unicode, stemming, stopwords, ranking, document updates, and access control before exposing an index to users.

04 Count the cost

TIME

Expected O(T) indexing for total text T; query depends on posting sizes plus O(r log r) output sort

SPACE

O(T) upper bound on token/posting storage

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Remove a document, rebuild the index, and verify that it no longer appears.

Reveal one possible solution +
one_possible_solution.py
import re
def tokens(text): return re.findall(r"[a-z]+", text.casefold())
def build_index(documents):
    index = {}
    for identity, text in documents.items():
        for token in set(tokens(text)):
            index.setdefault(token, set()).add(identity)
    return index
def search(index, query):
    terms = set(tokens(query))
    if not terms: return []
    postings = [index.get(term, set()) for term in terms]
    postings.sort(key=len)
    result = set(postings[0])
    for posting in postings[1:]: result.intersection_update(posting)
    return sorted(result)
documents = {1: "code tests", 2: "tests"}
index = build_index(documents)
assert search(index, "code") == [1]
del documents[1]
index = build_index(documents)
assert search(index, "code") == []
assert search(index, "") == []
print("Index lifecycle verified")

Definition of done

  • □Use one normalisation function for indexing and querying.
  • □Support multi-term AND queries.
  • □Return deterministic document ids.
  • □Return no matches for an unknown term or empty query.
  • □Demonstrate a correct document-removal rebuild.

06 Check your reasoning

QUICK SIGNAL CHECK

What must indexing and query processing share?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.