Sub topic 12
Building an inverted index
This chapter assumes you can read short Python snippets and know that earlier stages of the pipeline have already fetched a page and extracted its text. Here you build the data structure that makes search fast.
Why a forward scan does not scale
A crawler produces documents. A naive search would read every document and check whether it contains the query words. That cost grows with the size of the whole collection, which is far too slow for billions of pages.
An inverted index flips the relationship. Instead of mapping each document to its words, it maps each word (token) to the list of documents that contain it. That list is called a posting list. A query then looks up a few posting lists instead of scanning documents.
A working example
The code below indexes three small documents. It lowercases text and splits it on anything that is not a letter or digit. It stores each posting list as a set, so a word that appears twice in one document is recorded once.
import re
from collections import defaultdict
docs = {
1: "Search engines crawl web pages",
2: "Crawlers follow links to find web pages",
3: "An index maps words to pages",
}
def tokenize(text):
return re.findall(r"[a-z0-9]+", text.lower())
index = defaultdict(set)
for doc_id, text in docs.items():
for token in tokenize(text):
index[token].add(doc_id)
def search_all(query):
sets = [index.get(t, set()) for t in tokenize(query)]
return sorted(set.intersection(*sets)) if sets else []
print(search_all("web pages"))This prints [1, 2]. The token web maps to {1, 2} and pages maps to {1, 2, 3}. Their intersection is {1, 2}, so only those documents contain both words.
Two details matter in search_all. It calls index.get(t, set()) instead of index[t], because indexing a defaultdict with a missing key would silently add an empty entry. An unknown word gives an empty set, so the intersection is empty, which is the correct result for an "all words" query. The function also returns [] when the query has no tokens, because set.intersection(*sets) fails on an empty list.
Common errors
- Tokenizing queries differently from documents. If documents are lowercased but queries are not,
Webnever matchesweb. Use onetokenizefunction for both. - Duplicate postings. Appending to a list for every occurrence inflates the index and slows intersections. Store each document once per token, or store a count alongside it.
- Assuming "found" means "relevant". The index only answers which documents contain the words. Ranking is a separate step.
- Indexing text the crawler never saw. If a page depends on JavaScript, the index holds only what rendering produced.
What real indexes add
Production indexes extend this idea without changing it. They keep posting lists sorted by document ID, so intersections can walk two lists in step. They store term frequency and word positions to support ranking and phrase queries. They compress posting lists and split the index into shards across machines.
Exercise
Using the example's docs, what does search_all("index pages") return, and why?
Show answer
It returns [3]. The token index appears only in document 3, so its posting list is {3}. The token pages appears in documents 1, 2, and 3. The intersection of {3} and {1, 2, 3} is {3}.
Exercise
Why does the lookup use index.get(t, set()) instead of index[t]?
Show answer
index is a defaultdict, so index[t] creates an empty entry for every unknown query word and grows the index as a side effect. index.get(t, set()) returns an empty set without changing the index.