Algorithmcore
Blocked sort-based indexing
Also called BSBI.
Builds an inverted index on disk by sorting blocks of termid-docid pairs in memory and merging the sorted runs.
- Time
- O(T log T) worst · average · best
- Space
- O(T) diskO(M + V) memory
- Counts
- io O((T/B) (1 + log_(M/B) k)) worstio O(T/B) best
- Where
- B = the number of pairs in a disk block; M = the number of pairs that fit in memory; T = the number of tokens (one term id and document id pair for each); V = the number of distinct terms; k = the number of runs (the ceiling of T/M)
- Properties
- not comparison baseddeterministicnot in placeofflineiterativestable
- Evidence
- Proof sketchCode in 1 languages
Blocked sort-based indexing (BSBI) builds an inverted index for a collection that is too large for memory. It maps each term to an integer term id, reads the collection as a stream of (term id, document id) pairs, sorts the pairs one memory-sized block at a time, writes each sorted block to disk as a run, and then merges all runs into the final posting lists. It is external merge sort applied to term and document pairs, with two additions: a dictionary from terms to ids that stays in memory during the whole pass, and a merge that joins equal pairs into one posting with a term frequency. Single-pass in-memory indexing removes the global term ids and the sort of pairs; this page keeps both.
In plain words
A search engine must find, for each word, the list of documents that contain it. For a large collection this list of lists does not fit in memory. BSBI solves this with a method that most people use to sort a big pile of cards. First give each word a number. Then read the documents and write down, for each word you see, its number and the document number. When your memory is full, sort what you have, put the sorted stack on disk, and start a new stack. At the end, read all sorted stacks at the same time and always take the smallest card on top. The cards come out in order of word, and for each word in order of document. That is the index.
The problem
The input is a collection of documents , each a sequence of tokens, with tokens in total. The output is, for each distinct term , its posting list: the pairs for the documents that contain , in increasing order of , where is the number of times occurs in . Memory holds pairs, with much smaller than , and the disk transfers blocks of pairs. The machine is the external memory model. The dictionary of the distinct terms must fit in memory next to one block.
The algorithm
BSBI(D, M) ▷ D: documents in increasing id order, M ≥ 1- 1
termid ← empty map, runs ← empty list, block ← empty list - 2
for each document d of D, for each token w of d do - 3
if w is not in termid then termid[w] ← |termid| - 4
add (termid[w], d) to block - 5
if |block| = M then add INVERT(block) to runs, block ← empty list - 6
if block is not empty then add INVERT(block) to runs - 7
return MERGE-RUNS(runs) INVERT(block)- 8
sort block by (term id, document id) - 9
replace each group of equal pairs (t, d) by one triple (t, d, f), f the size of the group - 10
return the triples, in sorted order ▷ one run, written to disk MERGE-RUNS(runs)- 11
put the first triple of each run in a min-heap H, keyed by (t, d) - 12
while H is not empty do - 13
remove the least triple (t, d, f) of H, and put the next triple of its run in H - 14
if the last output triple has the key (t, d) then add f to its count - 15
else output (t, d, f) - 16
group the output by t, and map each term id back to its term
Line L1 starts an empty dictionary from terms to ids. The loop of line L2 reads the tokens in the order of the collection. Line L3 gives a new term the next free id. Line L4 adds one pair for each token. When the block holds pairs, line L5 sorts it and writes it out as one run, and line L6 does the same for the last, shorter block.
INVERT sorts a block by term id first and document id second (line L8). After the sort, the copies of one pair are next to each other, so line L9 can count them in one scan. The run holds one triple for each distinct pair of the block.
MERGE-RUNS is a k-way merge of the runs. The heap of line L11 holds the next triple of each run, so line L13 takes the triples of all runs in order of . A block can end in the middle of a document, so the same pair can appear in two runs. Line L14 joins such copies by adding their counts. Line L16 cuts the sorted output into one posting list for each term. In a real engine, the merge reads each run through a small buffer of a few disk blocks and writes each posting list to the index file as soon as its term is complete.
Example
The toy collection of the information retrieval pages has 8 documents of 9 or 10 tokens, 79 tokens in total, 50 distinct terms and 74 postings. Take . The term ids follow the order of first use: "binary" is 0, "search" is 1, "finds" is 2, "a" is 3, and "sorted" is 6. Line L5 cuts the stream after tokens 16, 32, 48 and 64, so there are runs.
| run | tokens | documents | triples | triples for "a" (id 3) and "sorted" (id 6) |
|---|---|---|---|---|
| 1 | 1 to 16 | 1, 2 | 15 | (3, 1, 2), (6, 1, 1), (6, 2, 1) |
| 2 | 17 to 32 | 2, 3, 4 | 16 | (3, 3, 1), (3, 4, 1), (6, 2, 1) |
| 3 | 33 to 48 | 4, 5 | 16 | (3, 4, 1), (6, 4, 1) |
| 4 | 49 to 64 | 5, 6, 7 | 15 | (3, 6, 2) |
| 5 | 65 to 79 | 7, 8 | 15 | (3, 7, 1), (6, 8, 1) |
Document 2 is "merge sort merges two sorted runs into one sorted array". Its first "sorted" is token 14 and goes to run 1, and its second "sorted" is token 18 and goes to run 2. The same happens to "a" in document 4, which runs 2 and 3 share. The merge reads these triples in this order:
| line L13 takes | from run | line | output |
|---|---|---|---|
| (3, 1, 2) | 1 | L15 | (3, 1, 2) |
| (3, 3, 1) | 2 | L15 | (3, 3, 1) |
| (3, 4, 1) | 2 | L15 | (3, 4, 1) |
| (3, 4, 1) | 3 | L14 | (3, 4, 2) |
| (3, 6, 2) | 4 | L15 | (3, 6, 2) |
| (3, 7, 1) | 5 | L15 | (3, 7, 1) |
| (6, 1, 1) | 1 | L15 | (6, 1, 1) |
| (6, 2, 1) | 1 | L15 | (6, 2, 1) |
| (6, 2, 1) | 2 | L14 | (6, 2, 2) |
| (6, 4, 1) | 3 | L15 | (6, 4, 1) |
| (6, 8, 1) | 5 | L15 | (6, 8, 1) |
The posting list of "a" is , and the list of "sorted" is . The five runs hold 77 triples. Line L14 joins three pairs that a block boundary cut: "sorted" in document 2, and "a" and "list" in document 4. So the index has postings, the same as a direct build in memory.
Correctness
The dictionary of line L3 gives each term one id for the whole pass, so equal terms in different blocks have equal ids. The blocks are consecutive pieces of the pair stream. In each run, line L9 outputs one triple for each distinct pair of the block, with the number of copies of that pair in the block. The heap merge outputs all triples in nondecreasing order of , so the copies of one pair from different runs come out one after the other, and line L14 adds their counts. The sum over the runs is the number of copies of in the whole stream, which is . Sorted by and then , the output is the posting lists in the required order. The full proof is in the proof file below.
Proof: Blocked sort-based indexing builds the same index as a direct in-memory buildfull
Let the input be documents with , where is the token sequence of document . Let . The reference index maps each term to the list of pairs with , sorted by , where is the number of times occurs in the tokens of . We show that BSBI with any block size returns .
-
The term ids are a bijection. Line L3 gives a term the id the first time the term is seen, and never changes it. So the ids are for the distinct terms, two different terms get different ids, and
term_ofinverts the map. From here on we identify a term with its id. -
The pair stream. Lines L2 to L4 produce one pair for each token, in reading order. Call this stream . For each , the number of copies of in is .
-
The blocks cover the stream. Line L5 cuts after every pairs, and line L6 flushes the last, shorter block if it is not empty. So the blocks are consecutive pieces of , their concatenation is , and . A block can end in the middle of a document, so one pair can have copies in two or more consecutive blocks.
-
Each run is correct for its block. Line L8 sorts block by . In a sorted sequence, equal pairs are next to each other, so the loop of line L9 sees each distinct pair of as one maximal group of equal elements and outputs one triple with the size of the group. So run holds exactly one triple for each pair that occurs in , where is its number of copies in , and the keys of are strictly increasing.
-
The merge outputs the triples in key order. The heap of lines L11 to L13 holds at most one triple of each run, the first triple of that run that is not yet output. This is the -way merge of sorted sequences: the least key in the heap is the least key not yet output, because each run is sorted. So line L13 removes the triples of all runs in nondecreasing order of , each one once.
-
Lines L14 and L15 join equal keys. Because the keys come out in nondecreasing order, all triples with one key come out one after the other. The first of them goes to the output by line L15, and each later one adds its count to that output triple by line L14. A triple with a new key starts a new output entry. So when the heap is empty, the output holds one triple for each distinct pair of , in strictly increasing key order. By steps 2 and 3, is the number of copies of in , which is .
-
Line L16 forms the lists. The output is sorted by and, for equal , by . Line L16 reads it in that order and appends to the list of term . So the list of each term holds its documents in increasing order of , with , and a term has a list exactly when it occurs in some document. This is .
The proof does not use the order of the document ids. With the ids in increasing order, as the input requires, one pair has copies in two runs only when a block boundary cuts document , and only the last document of a run can be cut.
Complexity
- CPU time. The blocks cost each to sort, so in total. The merge does work for each of at most triples. With , the total is , the cost of a sort of all pairs. This is the bound that Manning, Raghavan and Schuetze give for BSBI. The dictionary adds expected time with a hash table.
- Disk transfers. Reading the collection and writing the runs costs block transfers. If , one merge pass reads each run through a buffer of one block, so the merge also costs . If there are more runs than buffers, the runs are merged in passes of runs, as in external merge sort, and the merge costs .
- Memory. One block of pairs, plus the dictionary of terms, plus merge buffers.
- Disk. The runs hold at most triples. The final index replaces them.
Properties
- Two passes over the pairs. One pass writes the runs, and one merge pass reads them, when .
- Global term ids. The term to id map is built during the first pass and must stay in memory to the end. For a very large vocabulary this map can be the limit, not the block.
- Deterministic. The output does not depend on ; only the number and the content of the runs do.
- Sequential disk access. Each run is written once from start to end, and the merge reads each run from start to end.
Variants and improvements
- Two passes with a known vocabulary. If the vocabulary is collected in an earlier pass, the term ids can be the ranks of the terms in sorted order, so a merge by id is also a merge in term order.
- Compressed runs. The triples of a run are sorted, so the document ids of one term can be stored as gaps with a variable-length code. This cuts the disk space and the transfer time of the runs. See postings gap encoding.
- Merge-based construction. Buettcher, Clarke and Cormack describe sort-based construction with the same two phases, and compare it with merge-based construction, which builds a full in-memory index for each block and merges the partial indexes. That second method is close to SPIMI.
- Without global term ids. Single-pass in-memory indexing builds a dictionary and posting lists for each block, sorts only the terms of the block, and merges blocks by term string. It does not need the global map.
- Distributed construction. The same sort and merge steps run as the map and reduce phases of a MapReduce job, with term ranges as the partitions. See index partitioning.
When to use it
Use BSBI for a static collection that is larger than memory, when the dictionary of the whole vocabulary fits in memory and the sort of fixed-size records is the fastest tool at hand. For a collection that changes, BSBI builds the main index, and a scheme such as logarithmic merging adds new documents later. If the vocabulary is too large to keep a term to id map, use single-pass in-memory indexing.
Pitfalls
- Term ids for each block. If the map of line L1 is reset for each block, one term gets different ids in different runs, and the merge makes two posting lists for it. The map must live for the whole pass, as in line L1, or the merge must compare terms, as SPIMI does.
- No join of cut documents. If line L14 is left out and each triple goes to the output by line L15, the list of "sorted" in the example holds twice in place of . A block boundary can cut a document, so the merge must add the counts of equal pairs.
- Sort by term id only. An unstable sort by term id alone, in place of line L8, can put the documents of a term out of order inside a run, and the merged posting lists are then not sorted. The key must be the pair (term id, document id).
- Too many runs for one pass. The merge needs one buffer of at least one block for each run. If is larger than , a one-pass merge reads from disk with tiny buffers and becomes slow. Merge in several passes, as in external merge sort, or make the blocks larger.
- Pairs in place of postings. The block holds one pair for each token, not one for each distinct pair, so a block of pairs gives fewer than postings. The disk space for the runs is in tokens, not in postings.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/blocked-sort-based-indexing/. The authors are listed in prov/7YJRVM.jsonl.
import heapq
from typing import Iterable
Triple = tuple[int, int, int] # (term id, document id, term frequency)
def invert(block: list[tuple[int, int]]) -> list[Triple]:
"""Sort one block of (term id, doc id) pairs and group equal pairs.
Returns the run: the triples (t, d, f) in increasing order of (t, d), where f
is the number of times the pair (t, d) occurs in the block. Cost O(m log m)
for a block of m pairs.
"""
block.sort() # @line L8
run: list[Triple] = []
for t, d in block: # @line L9
if run and run[-1][0] == t and run[-1][1] == d:
run[-1] = (t, d, run[-1][2] + 1)
else:
run.append((t, d, 1))
return run # @line L10
def merge_runs(runs: list[list[Triple]], term_of: list[str]) -> dict[str, list[tuple[int, int]]]:
"""Merge sorted runs into one index with a min-heap, as a k-way merge.
Equal (t, d) keys from two runs, which come from a document cut by a block
boundary, are joined by adding their frequencies. Returns a map from each
term to its list of (doc id, tf) in increasing doc id order.
Cost O(P log k) for P triples in k runs.
"""
heap: list[tuple[int, int, int, int, int]] = []
for r, run in enumerate(runs): # @line L11
if run:
t, d, f = run[0]
heap.append((t, d, r, 0, f))
heapq.heapify(heap)
out: list[Triple] = []
while heap: # @line L12
t, d, r, pos, f = heapq.heappop(heap) # @line L13
if pos + 1 < len(runs[r]):
t2, d2, f2 = runs[r][pos + 1]
heapq.heappush(heap, (t2, d2, r, pos + 1, f2))
if out and out[-1][0] == t and out[-1][1] == d: # @line L14
out[-1] = (t, d, out[-1][2] + f)
else:
out.append((t, d, f)) # @line L15
index: dict[str, list[tuple[int, int]]] = {}
for t, d, f in out: # @line L16
index.setdefault(term_of[t], []).append((d, f))
return index
def bsbi(docs: Iterable[tuple[int, list[str]]], block_size: int) -> tuple[dict[str, list[tuple[int, int]]], list[list[Triple]]]:
"""Blocked sort-based indexing.
docs gives (doc id, tokens) in strictly increasing doc id order. block_size is
M, the number of (term id, doc id) pairs that fit in memory, M >= 1.
Returns the index (term -> list of (doc id, tf)) and the list of sorted runs
that the merge read. Cost O(T log M + P log k) time for T tokens, P triples
in the runs and k = ceil(T / M) runs.
"""
if block_size < 1:
raise ValueError("block_size must be at least 1")
termid: dict[str, int] = {} # @line L1
term_of: list[str] = []
runs: list[list[Triple]] = []
block: list[tuple[int, int]] = []
for d, tokens in docs: # @line L2
for w in tokens:
if w not in termid: # @line L3
termid[w] = len(term_of)
term_of.append(w)
block.append((termid[w], d)) # @line L4
if len(block) == block_size: # @line L5
runs.append(invert(block))
block = []
if block: # @line L6
runs.append(invert(block))
return merge_runs(runs, term_of), runs # @line L7
irtoy.py 76 lines
# SPDX-License-Identifier: MIT
# Shared helper of the information retrieval pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy collection of the information retrieval pages.
Eight short documents, four queries with graded judgments and one fixed
run. Tokens are the lower-case words split on spaces, with no stemming
and no stop words. The helper holds only the data and the statistics
tokenize, tf, df, cf, doc_len and avgdl. Scoring and metrics live on the
pages that define them.
"""
DOCS = {
1: "binary search finds a key in a sorted array",
2: "merge sort merges two sorted runs into one sorted array",
3: "an inverted index maps each term to a posting list",
4: "a posting list is a sorted list of document ids",
5: "skip pointers speed up the merge of two posting lists",
6: "a hash table finds a key in constant expected time",
7: "search engines rank documents by a score for the query",
8: "the sorted array of ids is compressed with gap encoding",
}
N = len(DOCS)
QUERIES = {
"q1": "sorted array search",
"q2": "posting list merge",
"q3": "rank documents",
"q4": "quantum circuit",
}
# Graded judgments: 2 is highly relevant, 1 is relevant, absent is 0.
QRELS = {
"q1": {1: 2, 2: 1, 8: 1},
"q2": {5: 2, 4: 1, 3: 1},
"q3": {7: 2},
"q4": {},
}
# A fixed run for the metric pages, as scores per query.
RUN = {
"q1": {1: 2.0, 6: 2.0, 8: 1.5, 2: 1.0, 4: 1.0},
}
def tokenize(text):
"""Lower-case words split on spaces."""
return text.lower().split()
_TOKENS = {d: tokenize(t) for d, t in DOCS.items()}
def tf(term, doc_id):
"""Number of times term occurs in document doc_id."""
return _TOKENS[doc_id].count(term)
def df(term):
"""Number of documents that contain term."""
return sum(1 for toks in _TOKENS.values() if term in toks)
def cf(term):
"""Number of occurrences of term in the whole collection."""
return sum(toks.count(term) for toks in _TOKENS.values())
def doc_len(doc_id):
"""Number of tokens in document doc_id."""
return len(_TOKENS[doc_id])
def avgdl():
"""Average document length in tokens."""
return sum(len(toks) for toks in _TOKENS.values()) / N
test_blocked_sort_based_indexing.py 85 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/blocked-sort-based-indexing/. The authors are listed in prov/7YJRVM.jsonl.
import math
import random
import irtoy
from blocked_sort_based_indexing import bsbi, invert
def direct_index(docs: list[tuple[int, list[str]]]) -> dict[str, list[tuple[int, int]]]:
"""The reference: one dictionary of dictionaries, built in memory."""
m: dict[str, dict[int, int]] = {}
for d, tokens in docs:
for w in tokens:
m.setdefault(w, {})
m[w][d] = m[w].get(d, 0) + 1
return {w: sorted(p.items()) for w, p in m.items()}
def toy_docs() -> list[tuple[int, list[str]]]:
return [(d, irtoy.tokenize(t)) for d, t in sorted(irtoy.DOCS.items())]
def check_runs(runs: list[list[tuple[int, int, int]]], tokens: int, m: int) -> None:
assert len(runs) == math.ceil(tokens / m)
for run in runs:
keys = [(t, d) for t, d, _ in run]
assert keys == sorted(set(keys))
assert sum(f for _, _, f in run) <= m
def test_toy_collection_block_16() -> None:
docs = toy_docs()
index, runs = bsbi(docs, 16)
assert index == direct_index(docs)
assert [len(r) for r in runs] == [15, 16, 16, 15, 15]
assert sum(len(r) for r in runs) == 77
assert len(index) == 50 and sum(len(p) for p in index.values()) == 74
assert index["sorted"] == [(1, 1), (2, 2), (4, 1), (8, 1)]
assert index["a"] == [(1, 2), (3, 1), (4, 2), (6, 2), (7, 1)]
check_runs(runs, 79, 16)
def test_toy_collection_every_block_size() -> None:
docs = toy_docs()
want = direct_index(docs)
for m in range(1, 90):
index, runs = bsbi(docs, m)
assert index == want
check_runs(runs, 79, m)
def test_invert_groups_pairs() -> None:
assert invert([(2, 5), (1, 7), (2, 5), (1, 3)]) == [(1, 3, 1), (1, 7, 1), (2, 5, 2)]
assert invert([]) == []
def test_edge_cases() -> None:
assert bsbi([], 3) == ({}, [])
assert bsbi([(1, []), (2, [])], 3) == ({}, [])
index, runs = bsbi([(4, ["x", "x", "x"])], 1)
assert index == {"x": [(4, 3)]} and len(runs) == 3
try:
bsbi([(1, ["x"])], 0)
except ValueError:
pass
else:
raise AssertionError("block size 0 was accepted")
def test_random_collections() -> None:
rng = random.Random(20261115)
for _ in range(600):
vocab = [f"w{i}" for i in range(rng.randint(1, 30))]
docs = []
d = 0
for _ in range(rng.randint(0, 12)):
d += rng.randint(1, 4)
docs.append((d, [rng.choice(vocab) for _ in range(rng.randint(0, 15))]))
tokens = sum(len(t) for _, t in docs)
m = rng.randint(1, 12)
index, runs = bsbi(docs, m)
assert index == direct_index(docs)
check_runs(runs, tokens, m)
History
Sort-based inversion of a text file is the classic method for building an inverted file, and Witten, Moffat and Bell describe it with the cost of the disk sort in their book on index construction. Manning, Raghavan and Schuetze gave the method the name blocked sort-based indexing in their 2008 textbook, where it is the first of the construction algorithms, next to single-pass in-memory indexing and distributed indexing. Buettcher, Clarke and Cormack treat it as sort-based index construction.
References
- Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 4, Section 4.1 (hardware basics) and Section 4.2 (blocked sort-based indexing, the BSBI pseudocode and the merge of the block files)
- Stefan Buettcher, Charles L. A. Clarke and Gordon V. Cormack, Information Retrieval, Implementing and Evaluating Search Engines, MIT Press, 2010, Chapter 4, Section 4.5 (index construction), Section 4.5.2 (sort-based index construction)
- Ian H. Witten, Alistair Moffat and Timothy C. Bell, Managing Gigabytes, second edition, Morgan Kaufmann, 1999, Chapter 5 (index construction, sort-based inversion)
- Justin Zobel and Alistair Moffat, Inverted files for text search engines, ACM Computing Surveys 38(2), Article 6, 2006, the section on index construction
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 7YJRVM Edit this page History Report an error Markdown