An Inverted Index by Hand
An inverted index maps each term to documents where it appears, enabling lookup by term rather than checking every document directly.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Build two postings
If document 1 contains tree and queue and document 2 contains tree and stack, the tree list contains 1 and 2. Queue maps to 1. A reverse index explains that change of lookup direction.
Choose additional stored information
Phrase searches can need positions, and scores can use term counts. A bare membership index can serve simple Boolean matching. See frequency maps for representing repeated terms per document.
from collections import defaultdict
postings = defaultdict(list)
documents = {1: ["tree", "queue", "tree"], 2: ["tree", "stack"]}
for document_id, tokens in sorted(documents.items()):
for token in set(tokens):
postings[token].append(document_id)
assert postings["tree"] == [1, 2]
Deduplicating tokens here records membership within one document. An index that scores term frequency needs to retain the two occurrences of tree in document 1 as a separate count.[1]
Build postings from distinct document identities
Three documents contain terms {rail,map}, {rail,station} and {map,route}. An inverted index stores one list per term naming documents that contain it. The posting for rail is shorter than scanning all document text in this example. See dictionary reverse indexes.
rail → [1,2]
map → [1,3]
station → [2]
route → [3]
Add extra posting data only for supported features
Frequencies help scoring, and positions help phrase search. Basic membership needs just document identity. Test removing document two and verifying that its old terms no longer return it.