Unit 5 · Index Construction¶
1. Setting the scene¶
Scenario: The overnight build that never finished
The inverted index from Unit 4 worked on 5,000 documents. For the full archive (2 million documents, ~400 million tokens) the Python script held every (term, docID) pair in a list, called sort(), and was killed by the operating system after two hours: out of memory.
The CityDocs server has 16 GB RAM and a large disk. New documents arrive every day, and some are withdrawn. The index must be rebuilt overnight and stay current during the day.
Guiding questions
- Why is disk access the real bottleneck, and which kind of disk access?
- How do we sort data that does not fit in memory?
- How do we split the work across machines?
- How do we add and delete documents without rebuilding everything?
2. Intended learning outcomes¶
| # | Outcome | Bloom | CLO |
|---|---|---|---|
| ILO 5.1 | Explain why disk seeks dominate index construction and why sequential I/O is preferred. | UNDERSTAND | 3 |
| ILO 5.2 | Apply Blocked Sort Based Indexing (BSBI) and estimate block sizes for a collection. | APPLY | 3 |
| ILO 5.3 | Compare BSBI and Single Pass In Memory Indexing (SPIMI). | ANALYSE | 3 |
| ILO 5.4 | Describe distributed indexing with MapReduce and distinguish term- and document partitioned indexes. | UNDERSTAND | 7 |
| ILO 5.5 | Explain dynamic indexing with auxiliary indexes, invalidation bit vectors and logarithmic merge. | UNDERSTAND | 3 |
3. Where we are¶
In earlier units we learned tokenisation, normalisation, the dictionary, postings lists, Boolean and tolerant retrieval. Today's question:
How do we build the inverted index efficiently when the collection is very large?
The naive algorithm is: read documents → emit (term, docID) → sort by term then docID → group into postings. The problem is the middle step: the number of postings \(T\) is far larger than main memory.
4. Hardware matters¶
CPU and RAM are fast. Disks are slow: not because reading is slow, but because of movement.
flowchart LR
S["Seek time<br/>move the head to the track<br/><b>very slow</b>"] --> R["Rotational delay<br/>wait for the sector<br/><b>slow</b>"] --> T["Transfer<br/>read the bytes<br/><b>fast</b>"]
During a seek no data is transferred. Disks read and write whole blocks (typically 8 to 256 KB). So: one large sequential read is far faster than many small random reads.
| Symbol | Statistic | Value |
|---|---|---|
| \(s\) | average seek time | 5 ms \(= 5 \times 10^{-3}\) s |
| \(b\) | transfer time per byte | 0.02 µs \(= 2 \times 10^{-8}\) s |
| processor clock rate | \(10^9\) s\(^{-1}\) | |
| \(p\) | low level operation (compare & swap) | 0.01 µs |
| main memory | several GB | |
| disk space | 1 TB or more |
Worked example: sequential vs. random
Reading 1 GB sequentially: \(10^9 \times 2\times10^{-8}\,\text{s} = 20\) s.
Reading the same 1 GB as one million random 1 KB chunks: \(10^6 \times 5\,\text{ms} = 5{,}000\) s of seeking alone: 250× slower.
Design rule: read and write large blocks sequentially. (SSDs shrink the gap but do not remove it; the same principle guides modern systems.)
A second hardware lesson: large IR systems scale out with many commodity machines rather than scaling up one expensive server, and they must tolerate failures of individual machines.
5. The model collection: Reuters RCV1¶
| Statistic | Value |
|---|---|
| Documents \(N\) | 800,000 (one year of Reuters newswire, 1995 to 1996) |
| Avg. tokens per document \(L\) | 200 |
| Distinct terms \(M\) | 400,000 |
| Avg. bytes per token | 4.5 (without spaces/punctuation): 6 |
| Avg. bytes per term | 7.5 |
| Nonpositional postings | 100,000,000 |
Even a medium sized news collection produces 100 million postings.
Why sorting is the key step, and why it hurts¶
Postings arrive in document order: (caesar,1) (died,1) (brutus,2) (killed,2) (caesar,2). Sorting by term groups them: (brutus,2) (caesar,1) (caesar,2) (died,1) (killed,2) → caesar → [1, 2].
A comparison sort needs about \(T \log_2 T\) comparisons: \(10^8 \times 27 \approx 2.7 \times 10^9\). In memory that is seconds; if each comparison could trigger a disk seek, it would take years. We need external sorting.
6. Blocked Sort Based Indexing (BSBI)¶
flowchart LR
subgraph P["Pass 1 · per block, in memory"]
direction TB
B1["Block 1 raw"] --> R1["Run 1 sorted"]
B2["Block 2 raw"] --> R2["Run 2 sorted"]
B3["Block 3 raw"] --> R3["Run 3 sorted"]
end
R1 & R2 & R3 --> M["Pass 2 · multiway merge<br/>sequential reads, one output stream"]
M --> F[("Final inverted index")]
- Parse the next block of documents into
(termID, docID)pairs. - Sort the block in memory (termID, then docID).
- Write the sorted block (a run) to disk.
- After all blocks: merge all runs in one multiway merge.
BSBIIndexConstruction()
1 n ← 0
2 while (all documents have not been processed)
3 n ← n + 1
4 block ← ParseNextBlock()
5 BSBIInvert(block) // sort pairs in memory
6 WriteBlockToDisk(block, f_n)
7 MergeBlocks(f_1, …, f_n ; f_merged)
Worked example: sizing BSBI for RCV1
Each posting record is (termID, docID, frequency) at 4 bytes each = 12 bytes.
\(10^8 \times 12\) bytes \(= 1.2\) GB: uncomfortable to sort in memory at once.
Split into 10 blocks of 120 MB: each fits in memory and is sorted there, written as a run, and the 10 runs are merged by reading a buffer from each run and writing one sequential output.
Multiway merge. Runs a b c, a d f, b c e, a g h are merged by repeatedly taking the smallest head term (a priority queue): a ← runs 1, 2, 4; b ← runs 1, 3; … All reads and writes are sequential.
Worked example: a cost model for BSBI on RCV1
Use the hardware table from Section 4 (\(s = 5\) ms per seek, \(b = 2 \times 10^{-8}\) s per byte, \(p = 10^{-8}\) s per comparison) and 10 blocks of \(10^{7}\) records (120 MB each).
Sorting one block: \(10^{7} \log_2 10^{7} \approx 2.3 \times 10^{8}\) comparisons, i.e. \(2.3\) s; all blocks together about \(23\) s.
Transfer: the 1.2 GB of runs are written once, read once for the merge, and the final index is written once:
Seeks during the merge depend on the read buffer per run. With 10 MB buffers the merge needs \(1.2\ \text{GB} / 10\ \text{MB} = 120\) refills, \(0.6\) s of seeking. With 4 KB buffers it needs \(3 \times 10^{5}\) refills, 1,500 s. The algorithm is the same; the buffer size decides whether the disk seeks or streams.
gantt
title BSBI on one machine (simplified, seconds)
dateFormat X
axisFormat %s
section Block 1
parse and sort :0, 5
write run :5, 7
section Block 2
parse and sort :7, 12
write run :12, 14
section Block 3
parse and sort :14, 19
write run :19, 21
section Merge
multiway merge of all runs :21, 30
With \(n\) runs and a merge that can read \(k\) runs at once, the number of merge passes is
so 10 runs and \(k \ge 10\) need a single pass.
BSBI's weakness
BSBI maps terms to termIDs, which requires a global dictionary in memory (caesar → 15). For very large or continuously growing collections the dictionary itself may not fit, and keeping termIDs consistent across blocks is expensive.
7. Single Pass In Memory Indexing (SPIMI)¶
Two key ideas:
- A separate dictionary per block: no global term → termID mapping; terms are stored as strings.
- No sorting of postings: postings are appended directly to each term's list as tokens stream in.
flowchart TB
subgraph R1["Read"]
direction LR
D["Documents"] --> TS["Token stream<br/>(term, docID)"] --> BL["Block = as much of<br/>the stream as fits<br/>in memory"]
end
subgraph R2["Invert one block"]
direction LR
BI["Block index<br/>hash: term → postings"] --> SO["Sort the terms<br/>(not the postings)"] --> W["Write block<br/>to disk"]
end
subgraph R3["Merge"]
direction LR
MG[("Merge block indexes<br/>→ final index")]
end
R1 --> R2 --> R3
SPIMIInvert(token_stream)
1 output_file ← NewFile()
2 dictionary ← NewHash()
3 while (free memory available)
4 token ← next(token_stream)
5 if term(token) ∉ dictionary
6 then postings_list ← AddToDictionary(dictionary, term(token))
7 else postings_list ← GetPostingsList(dictionary, term(token))
8 if full(postings_list)
9 then postings_list ← DoublePostingsList(dictionary, term(token))
10 AddToPostingsList(postings_list, docID(token))
11 sorted_terms ← SortTerms(dictionary)
12 WriteBlockToDisk(sorted_terms, dictionary, output_file)
13 return output_file
from collections import defaultdict
import heapq
def spimi_invert(token_stream, max_postings=4):
"""Consume (term, docID) pairs; yield a sorted block index whenever 'memory' is full."""
block, used = defaultdict(list), 0
for term, doc_id in token_stream:
postings = block[term] # new term → new list, no global termID
if not postings or postings[-1] != doc_id:
postings.append(doc_id)
used += 1
if used >= max_postings: # memory full → write the block
yield dict(sorted(block.items()))
block, used = defaultdict(list), 0
if block:
yield dict(sorted(block.items()))
def merge_blocks(blocks):
"""Multi-way merge of sorted block indexes."""
merged = defaultdict(list)
streams = [iter(b.items()) for b in blocks]
for term, postings in heapq.merge(*streams, key=lambda kv: kv[0]):
merged[term].extend(postings)
return {t: sorted(set(p)) for t, p in merged.items()}
docs = {1: "caesar died", 2: "brutus killed caesar", 3: "caesar was ambitious"}
stream = ((t, d) for d, text in docs.items() for t in text.split())
print(merge_blocks(list(spimi_invert(stream))))
| Aspect | BSBI | SPIMI |
|---|---|---|
| Main idea | Sort term, document pairs | Build postings lists directly |
| Dictionary | Global, in memory (term → termID) | Separate per block |
| Sorting | Sorts all pairs in each block | Sorts only the terms of a block |
| Memory use | Needs termID mapping | Simpler, no mapping |
| Block output | Sorted run of pairs | Small complete inverted index |
| Final step | Merge runs | Merge block indexes |
SPIMI can also compress postings as it writes them (for example storing gaps [1, 5, 9, 11] → [1, 4, 4, 2]), so less data is written and merged (Unit 6).
8. Distributed indexing¶
For web scale collections one machine is not enough. Distributed indexing uses many commodity machines coordinated by a master, which assigns tasks and reassigns them when a machine fails.
flowchart LR
subgraph S["Splits"]
S1["Split 1"]
S2["Split 2"]
S3["Split 3"]
end
subgraph PA["Parsers (map)"]
P1["Parser"]
P2["Parser"]
P3["Parser"]
end
subgraph IN["Inverters (reduce)"]
I1["Inverter a to f"]
I2["Inverter g to p"]
I3["Inverter q to z"]
end
S1 --> P1
S2 --> P2
S3 --> P3
P1 & P2 & P3 --> I1 & I2 & I3
I1 --> O1[("Postings a to f")]
I2 --> O2[("Postings g to p")]
I3 --> O3[("Postings q to z")]
- Parsers read documents and emit
(term, docID)pairs, written into term range partitions. - Inverters collect all pairs for one term range and build the postings lists.
This is exactly MapReduce (Unit 2):
Worked example: MapReduce indexing
Input: d1 caesar came caesar, d2 caesar died
Map → (caesar,d1) (came,d1) (caesar,d1) (caesar,d2) (died,d2)
Shuffle (group by term) → caesar → [d1, d1, d2], came → [d1], died → [d2]
Reduce (build postings with term frequencies) → caesar → [(d1:2), (d2:1)], came → [(d1:1)], died → [(d2:1)]
The master keeps the job alive when machines fail:
sequenceDiagram
participant M as Master
participant P1 as Parser 1
participant P2 as Parser 2
participant I as Inverter a to f
M->>P1: parse split 1
M->>P2: parse split 2
P1-->>I: pairs for terms a to f
Note over P2: machine crashes
M->>M: no heartbeat from Parser 2
M->>P1: parse split 2 (reassigned)
P1-->>I: pairs for terms a to f
M->>I: all splits done, build postings
I-->>M: postings for a to f written
Term partitioned vs. document partitioned indexes¶
| Term partitioned | Document partitioned | |
|---|---|---|
| Split | Machine 1: terms a to f; machine 2: g to p; … | Machine 1: docs 1 to 1M; machine 2: 1M to 2M; … |
| Natural for | Building the index (output of inverters) | Serving queries |
| Query processing | A multiterm query hits several machines, which must exchange long postings lists | Every machine answers the query over its own documents in parallel; results are merged |
Most large search engines serve from document partitioned indexes. (Caveat: global statistics such as IDF must be shared across partitions.)
9. Dynamic indexing¶
Real collections change: documents are added, deleted and updated, and new terms appear. Rebuilding the whole index for each change is too expensive.
flowchart TB
NEW["New documents"] --> AUX["Auxiliary index<br/>small, in memory"]
MAIN[("Main index<br/>large, on disk")]
Q["Query"] --> MAIN & AUX
MAIN & AUX --> F["Merge results + filter deleted docs<br/>(invalidation bit vector)"] --> RES["Results"]
AUX -.->|"periodic merge<br/>when too large"| MAIN
Invalidation bit vector. Deleted documents are not removed from postings immediately; they are marked invalid and filtered at query time.
An update = delete + reinsert.
Logarithmic merge¶
Merging the auxiliary index into one huge main index again and again rewrites the same postings many times and hurts query performance during merges. Logarithmic merge keeps a series of indexes \(I_0, I_1, I_2, \dots\), each about twice the size of the previous one, like carrying in binary addition.
flowchart TB
Z["Z₀ in memory fills up"] -->|"write"| I0["I₀ · size 1"]
I0 -->|"collision: merge"| I1["I₁ · size 2"]
I1 -->|"collision: merge"| I2["I₂ · size 4"]
I2 -->|"collision: merge"| I3["I₃ · size 8 …"]
| Step | Event | Indexes afterwards |
|---|---|---|
| 1 | Doc1 | \(I_0 = [1]\) |
| 2 | Doc2 → \(I_0\) occupied → merge | \(I_1 = [1, 2]\) |
| 3 | Doc3 | \(I_0 = [3]\), \(I_1 = [1, 2]\) |
| 4 | Doc4 → cascade: \(I_0{+}I_0 \to I_1\), \(I_1{+}I_1 \to I_2\) | \(I_2 = [1, 2, 3, 4]\) |
Each posting is merged \(O(\log(T/n))\) times instead of \(O(T/n)\), at the price of querying up to \(\log(T/n)\) indexes.
Worked example: why logarithmic merge pays off
Suppose the auxiliary index is flushed \(k\) times, each flush holding one block. Naive merging rewrites the whole main index at every flush, so after \(k\) flushes it has written
Logarithmic merge moves each block at most \(\log_2 k\) times, about \(k \log_2 k\) block writes in total.
For \(k = 128\): naive \(8{,}256\) block writes, logarithmic \(128 \times 7 = 896\), about 9× less, and the gap grows with \(k\).
xychart-beta
title "Blocks written after k flushes"
x-axis "Flushes k" [16, 32, 64, 128]
y-axis "Block writes" 0 --> 9000
line [136, 528, 2080, 8256]
line [64, 160, 384, 896]
Upper line: naive merge; lower line: logarithmic merge.
10. Classwork: a mini Wikipedia search engine¶
Build it (45 min, teams of two)
flowchart TB
subgraph R1["Collect"]
direction LR
A["1 · Seed topic<br/>e.g. Information Retrieval"] --> B["2 · Fetch 5 to 10 pages"] --> C["3 · Parse and clean"]
end
subgraph R2["Map"]
direction LR
D["4 · Tokenise"] --> E["5 · Map: emit<br/>(term, pageID)"]
end
subgraph R3["Reduce and search"]
direction LR
F["6 · Shuffle + Reduce:<br/>inverted index"] --> G["7 · Answer a query"]
end
R1 --> R2 --> R3
Use the wikipedia or requests package, your Unit 3 preprocessing and the SPIMI code above. Report: vocabulary size, number of postings, and the result of two AND queries.
11. Check your understanding¶
Why does BSBI need termIDs, and why is that a problem at web scale?
Fixed width integer termIDs make pairs compact and fast to sort. Mapping terms to IDs requires a global dictionary in memory; at web scale the vocabulary keeps growing (Heaps' law, Unit 6) and may not fit.
Where does SPIMI save work compared to BSBI?
It never sorts individual (term, docID) pairs; postings are appended in docID order as they arrive, and only the block's terms are sorted before writing.
Why do search engines serve from document partitioned indexes?
Every machine can evaluate the whole query on its own subset of documents, in parallel and with local postings; only small top k result lists travel over the network.
12. Key takeaways¶
- Index construction is dominated by disk seeks: design for sequential I/O.
- BSBI: sort blocks in memory, write runs, multiway merge (needs a global termID dictionary).
- SPIMI: per block dictionaries, postings built directly, no pair sorting; simpler and faster.
- Distributed indexing = MapReduce: parsers map, inverters reduce by term range.
- Dynamic indexing: auxiliary index + invalidation bit vector; logarithmic merge reduces remerging.
13. Link to assessment¶
If your project uses a large dataset or the optional big data stack, document how your index is built (in memory, SPIMI style blocks, or Spark MapReduce) and how new documents are added. This is part of the architecture criterion in the rubric.
Further reading¶
- Manning, Raghavan & Schütze, Introduction to IR, ch. 4.
- Dean & Ghemawat (2004), MapReduce: Simplified Data Processing on Large Clusters.