Sub topic 12
Building an inverted index
This chapter assumes you can read short Python snippets and know what a crawler hands to the indexer: the extracted text of each fetched page, after rendering and canonicalization. Here you build the data structure that lets a search engine answer a query without scanning every page.
Why a forward index is not enough
A crawler produces documents, and each document contains words. Storing it that way gives a forward index: document ID to list of words. To find pages containing "crawl", you would read every document. That cost grows with the size of the web.
An inverted index flips the mapping. Each term points to the list of documents that contain it. That list is called a postings list, and each entry in it is a posting. Answering a query becomes a lookup of a few terms plus some list operations, not a scan of the corpus.
| Structure | Maps | Good for | Cost of "which pages contain X?" |
|---|---|---|---|
| Forward index | document to terms | building and updating a document | Scan every document |
| Inverted index | term to documents | answering queries | Look up one term |
From pages to postings
The index builder runs after tokenization. The stages are:
- Take the canonical URL's extracted text and assign the document an ID.
- Tokenize the text into normalized terms.
- For each term, add the document ID to that term's postings list.
- Keep postings lists sorted by document ID so they can be merged quickly.
The same tokenizer must run on queries. If the index stores pages but the query is looked up as Pages, the lookup fails even though the page matches.
A minimal working index
The following code builds an index over three small documents and answers a multi-word query with AND semantics.
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 term web maps to {1, 2} and pages maps to {1, 2, 3}. The intersection is {1, 2}.
Three details are worth noticing:
index.get(t, set())is used instead ofindex[t]. On adefaultdict,index[t]would create an empty entry for every unknown query term and slowly grow the index with junk.- An unknown term gives an empty set, so the AND intersection is empty. That is the correct behavior: no page contains all the words.
- The
if setsguard handles an empty query.set.intersection()with no arguments raises an error.
Merging sorted postings
Python sets are convenient, but production indexes store postings as sorted arrays of integers. Sorted lists allow a linear-time merge with no hashing, and they compress well.
def intersect(a, b):
i = j = 0
out = []
while i < len(a) and j < len(b):
if a[i] == b[j]:
out.append(a[i])
i += 1
j += 1
elif a[i] < b[j]:
i += 1
else:
j += 1
return out
print(intersect([1, 2, 3], [1, 2]))This prints [1, 2]. The cost is proportional to the sum of the two list lengths. A common optimization is to intersect the shortest lists first, so intermediate results stay small.
OR queries use a union merge instead. NOT queries subtract one list from another. Most web engines treat a plain multi-word query as AND at the candidate stage, then rank the candidates.
Storing positions for phrase queries
A document ID alone cannot tell you whether "web pages" appears as a phrase or whether web and pages are just both present. To answer phrase queries, each posting also stores the positions of the term in the document.
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(lambda: defaultdict(list))
for doc_id, text in docs.items():
for pos, token in enumerate(tokenize(text)):
index[token][doc_id].append(pos)
def phrase_search(phrase):
tokens = tokenize(phrase)
if not tokens:
return []
postings = [index.get(t) for t in tokens]
if any(p is None for p in postings):
return []
candidates = set(postings[0])
for p in postings[1:]:
candidates &= set(p)
results = []
for doc_id in sorted(candidates):
for start in postings[0][doc_id]:
if all(start + i in postings[i][doc_id] for i in range(1, len(tokens))):
results.append(doc_id)
break
return results
print(phrase_search("web pages"))
print(phrase_search("pages web"))
print(phrase_search("to pages"))The output is:
[1, 2]
[]
[3]The search first finds documents containing every term, then checks that the positions line up as consecutive offsets. pages web has both words in documents 1 and 2, but in the wrong order, so it fails the position check. to pages matches only document 3, where the words are adjacent. In document 2 they are separated by find web.
Positions make the index larger. Many engines store them anyway because phrase matching and proximity ranking depend on them.
Term frequency and what else postings carry
A posting can hold more than an ID. Typical extra fields are:
- Term frequency, the number of times the term appears in the document, used by ranking functions.
- Positions, as shown above.
- Field flags, such as whether the term appeared in the title, a heading, or anchor text.
The index stores facts about the page. Ranking, covered in the next chapter on serving, decides how to weigh them.
Common errors
- Mismatched normalization. Indexing with lowercase tokens and querying with raw text produces silent misses. Share one tokenizer function.
- Indexing the wrong text. If rendering did not run, a JavaScript-built page may yield an almost empty document, and its real content never reaches the index. The index can only contain what the earlier stages delivered.
- Indexing duplicates. If canonicalization did not collapse
?utm_source=xvariants, the same text lands in several postings under different IDs. Results then show near-identical pages. - Indexing pages marked
noindex. The builder must honor the directive, which is the subject of the next chapter. Anoindexpage may be fetched and parsed, but its terms are excluded from the postings. - Never removing old postings. When a page changes, the old terms must be deleted. Otherwise a query matches words that are no longer on the page.
- Unbounded stop-word dropping. Removing common words like
tosaves space but breaks phrase queries such as "to be or not to be". Many modern engines keep them.
How this scales
The structure you built is the same one large systems use. The differences are engineering:
- Postings are compressed, often by storing the gaps between sorted document IDs instead of the IDs themselves, because small gaps take fewer bytes.
- The term dictionary is kept in a compact searchable structure, so a lookup needs little memory.
- The index is split into shards, each holding a subset of documents. A query goes to every shard, and the partial results are combined.
Check your understanding
Exercise
Using the three documents above, what does the postings list for the term to contain, and what does search_all("to pages") return? Why does the phrase search for "to pages" return only document 3?
Show answer
The term to appears in documents 2 and 3, so its postings list is {2, 3}. Because pages appears in {1, 2, 3}, the AND intersection search_all("to pages") returns [2, 3]. The phrase search returns only [3] because it also requires the positions to be consecutive. In document 3 the words are adjacent ("to" at position 4, "pages" at position 5). In document 2, "to" is at position 3 and "pages" at position 6, with "find web" between them.
Exercise
A site owner reports that searching for a word that clearly appears on their page returns nothing. The page was crawled successfully. Name two index-building causes you would check first.
Show answer
First, check whether the text was present when the page was indexed. A JavaScript-dependent page that was not rendered may have contributed almost no terms. Second, check whether the indexer excluded the page, for example because of a noindex directive or because it was treated as a duplicate of another canonical URL. A tokenizer mismatch between indexing and querying is a third possibility.