Sub topic 2
How an inverted index works
This chapter assumes you know basic SQL and what a database index is. It explains the data structure that nearly every search engine is built on, and why it answers text queries quickly where a table scan cannot.
The problem with scanning
A query like WHERE name LIKE '%jacket%' has to read every row and check the text. A B-tree index doesn't help, because the match can start anywhere in the string. Cost grows with the size of the table.
An inverted index flips the lookup. A normal (forward) index goes from a document to its words. An inverted index goes from a word to the documents that contain it. The words are called terms, and the list of documents for a term is called its postings list.
Building one
Take three documents:
| ID | Text |
|---|---|
| 1 | Red running shoes |
| 2 | Blue running jacket |
| 3 | Red jacket |
Splitting each text into lowercase terms and recording which documents contain each term gives this index:
| Term | Postings list |
|---|---|
| red | 1, 3 |
| running | 1, 2 |
| shoes | 1 |
| blue | 2 |
| jacket | 2, 3 |
To find documents containing "jacket", you look up one entry and read its list. The cost depends on the number of matches, not the number of documents.
A minimal implementation
This Python code builds the index and answers an AND query by intersecting postings.
import re
docs = {
1: "Red running shoes",
2: "Blue running jacket",
3: "Red jacket",
}
def tokenize(text):
return re.findall(r"[a-z0-9]+", text.lower())
index = {}
for doc_id, text in docs.items():
for term in set(tokenize(text)):
index.setdefault(term, set()).add(doc_id)
def search(query):
postings = [index.get(t, set()) for t in tokenize(query)]
return set.intersection(*postings) if postings else set()
print(search("red jacket")) # {3}The query "red jacket" looks up two postings lists, {1, 3} and {2, 3}, and intersects them to get {3}. Replacing intersection with union gives OR semantics, which matches any term.
What real engines add
The sketch above stores only document IDs. Production engines store more per term:
- Term frequency. How many times the term appears in each document. Ranking uses this.
- Positions. Where in the document each occurrence sits. Phrase queries such as "running shoes" need this to check that the words are adjacent.
- Sorted postings. Lists are kept sorted by document ID and compressed. Sorting lets the engine intersect two lists with a single linear merge instead of repeated lookups.
- A term dictionary. The set of terms is stored in a structure that supports fast prefix and exact lookup, so finding a term's postings list is cheap even with millions of terms.
Common errors
- Assuming the index sees raw text. The index holds whatever terms the tokenizer produced. If "Running" is lowercased at index time but a query is not, the lookup misses. Index-time and query-time processing must agree. The next chapter covers this.
- Expecting substring matches. The index matches whole terms. Searching "jack" will not find "jacket" unless you add prefix or n-gram handling.
- Treating the index as free. Writes cost more than in a plain table, because one document updates many postings lists. Engines batch writes into immutable segments, which is part of why search results lag behind the database. Later chapters return to this.
Exercise
Using the three documents above, what postings lists would the index hold for "running" and "shoes", and what does the query "running shoes" return with AND semantics?
Show answer
"running" maps to documents 1 and 2, and "shoes" maps to document 1. The intersection is {1}, so the query returns only document 1 ("Red running shoes").
Exercise
Why can an inverted index answer a phrase query like "running shoes" only if it stores term positions?
Show answer
Intersecting postings tells you that both terms appear in a document, but not that they appear next to each other. Positions let the engine check that "shoes" occurs immediately after "running".