Inverted indexes: from a word to its documents and positions
倒排索引
Build positional postings, evaluate exact phrases and decode document gaps.
inverted-indexAsk the word where it occurs
A document-oriented store answers “what words are in document 5?” An inverted index reverses the lookup: “which documents contain cable?” In our nine invented records, the answer is 0,3,5,7. Searching those postings can avoid reading every document again. The structure accelerates access; it does not decide whether a bicycle or car record meets the user’s need.
A dictionary maps each indexed term to its postings. A posting can contain a document ID, frequency and positions, depending on what was stored. The IIR textbook presents this as a sparse alternative to a full term-by-document matrix. Our implementation adds exact token positions so that a phrase can be checked. IIR, sections 1.2 and 2.4
Presence, frequency and position are different data
Let d be a document ID and p a zero-based token position after analysis. A positional postings list groups all occurrences of term t by document:
Document frequency is the number of document entries, not the number of positions. In the example, cable occurs in four documents but has six total occurrences because document 5 repeats it three times. Sorting document IDs supports merging lists; sorting positions supports ordered phrase checks.
For a phrase t_0,…,t_(m−1), a starting position p must satisfy every offset constraint. Intersecting the document sets first narrows the candidates, but does not establish that the words are adjacent:
This also handles repeated terms. Positions 3,4,5 for cable produce starts 3 and 4 for “cable cable.” The program keeps all tokens; dropping stopwords or inserting position gaps requires a declared positional policy.
For sorted document IDs, store differences instead of full IDs. With the first ID kept as its own gap, cumulative sums recover the originals:
IDs start at zero here, so the first gap can be zero. Our variable-byte convention uses seven payload bits per byte and sets the high bit on the final byte. For nonnegative integer g, its encoded length is:
This is a simple teaching codec consistent with the book’s final-byte convention, not Lucene’s on-disk format. Compression saves space for small gaps; large gaps can take more than one byte. IIR, section 5.3.1
Trace a phrase through the index
Use Python 3.12 and the standard library. The same analyzer is used for records and queries: lowercase ASCII letter sequences, no stemming or stopword removal. Building the index records each token once at its position. A live-document set controls which IDs can appear in results; removing an ID from that set does not rewrite its stored postings.
import json,math,re
from collections import Counter,defaultdict
DOCUMENTS=(
'repair bicycle brake cable',
'bicycle brake adjustment guide',
'bicycle paint blue frame',
'car brake cable repair',
'cycle stopping wire replacement',
'repair bicycle brake cable cable cable',
'',
'brake cable bicycle repair',
'cell cycle stopping research',
)
def tokens(text):
if not isinstance(text,str) or len(text)>2000:raise ValueError('text of at most2000 characters required')
return re.findall(r'[a-z]+',text.lower())
def corpus(documents):
if not isinstance(documents,(list,tuple)) or not 1<=len(documents)<=100:raise ValueError('one to100 documents required')
return [tokens(d) for d in documents]
def build(documents=DOCUMENTS):
rows=corpus(documents);index={}
for doc,ts in enumerate(rows):
for position,term in enumerate(ts):index.setdefault(term,{}).setdefault(doc,[]).append(position)
return index
def phrase(query,index,live):
terms=tokens(query)
if not terms:return {}
candidates=set(live)
for term in terms:candidates.intersection_update(index.get(term,{}))
hits={}
for doc in sorted(candidates):
starts=set(index[terms[0]][doc])
for offset,term in enumerate(terms[1:],1):starts.intersection_update(p-offset for p in index[term][doc])
if starts:hits[doc]=sorted(starts)
return hits
def gaps(ids):
if any(type(x) is not int or not 0<=x<2**31 for x in ids) or any(a>=b for a,b in zip(ids,ids[1:])):raise ValueError('strictly increasing bounded nonnegative IDs required')
return [x-(ids[i-1] if i else 0) for i,x in enumerate(ids)]
def encode(numbers):
out=[]
for n in numbers:
if type(n) is not int or not 0<=n<2**31:raise ValueError('bounded nonnegative integer required')
parts=[n%128];n//=128
while n:parts.insert(0,n%128);n//=128
parts[-1]|=128;out.extend(parts)
return out
def decode(data):
if any(type(x) is not int or not 0<=x<=255 for x in data):raise ValueError('byte integers required')
out=[];value=0;size=0
for byte in data:
value=128*value+(byte&127);size+=1
if value>=2**31 or size>5:raise ValueError('integer overflow')
if byte&128:out.append(value);value=0;size=0
if size:raise ValueError('unterminated integer')
return out
def demo():
index=build();ids=sorted(index['cable']);delta=gaps(ids);wire=encode(delta);decoded=decode(wire);restored=[];total=0
for d in decoded:total+=d;restored.append(total)
live=set(range(len(DOCUMENTS)));postings={t:[dict(doc=d,positions=pos) for d,pos in sorted(rows.items())] for t,rows in sorted(index.items())}
return dict(documents=list(DOCUMENTS),postings=postings,terms=len(index),document_term_pairs=sum(len(r) for r in index.values()),positions=sum(len(p) for r in index.values() for p in r.values()),cable_docids=ids,cable_gaps=delta,cable_bytes=wire,restored_docids=restored,uncompressed_docid_bytes=4*len(ids),encoded_docid_bytes=len(wire),phrase_brake_cable=phrase('brake cable',index,live),phrase_bicycle_brake=phrase('bicycle brake',index,live),repeated_term_phrase=phrase('cable cable',index,live),without_doc5=phrase('cable cable',index,live-{5}),scope='Exact token positions and a simple final-high-bit variable-byte codec; not Lucene format or whole-index compression.')
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
The fixture has 16 distinct terms, 32 document–term pairs and 34 positions. “bicycle brake” matches documents 0,1,5, but not document 7, whose words are reordered. “cable cable” matches document 5 twice, at starts 3 and 4; removing ID 5 from the live set removes both matches.
Cable’s IDs 0,3,5,7 become gaps 0,3,2,2 and bytes 128,131,130,130. Decoding and cumulative addition restore the IDs. Those four IDs need four encoded bytes instead of sixteen bytes in a fixed 32-bit representation. This comparison excludes the dictionary, frequencies, positions and Python object overhead; it is not a whole-index compression ratio.
For T tokens, dictionary insertion has expected O(T) work under the hash-table model. Documents are visited in increasing ID order. Storing every position requires O(T) positions plus dictionary and document-entry overhead. Our phrase checker uses sets to narrow candidates and intersect shifted positions; its work is proportional to the postings and positions it actually reads, with sorting of output IDs and positions added. It is not an optimized compressed-list iterator.
A feature not indexed cannot be recovered by a flag
Lucene’s PostingsEnum distinguishes frequencies, positions and character offsets. Its documentation specifies that absent indexed positions yield −1, and position access has iterator preconditions. Requesting a feature is not the same as having stored it. Our token offsets are not character offsets, and our functions are not a Java API reproduction. PostingsEnum
A production index needs update and deletion policies, durability, segment management and a way to keep the analyzer consistent with queries. The live-set filter here is only a small deletion example. A positionless index can establish co-occurrence but needs another source of word order to verify a phrase. For a tiny corpus, a direct scan is simpler and supplies an independent correctness oracle.
The decoder rejects truncated byte streams and integers outside the declared 31-bit domain. It does not implement checksums or authenticate stored data. Its limited integer stream demonstrates a space tradeoff, while Boolean retrieval explains how postings are combined to satisfy conditions.
Inspect the stored evidence
- Cable appears three times in document 5. Does it add three to document frequency?
Answer: No. That document contributes one document entry and three positions. Across the fixture, document frequency is four and total occurrence count is six.
- Why does document 7 fail “bicycle brake” although it contains both words?
Answer: Its sequence is brake, cable, bicycle, repair. There is no bicycle position immediately followed by brake. Set membership loses the needed order.
- Decode bytes 128,131,130,130 as gap-coded document IDs.
Answer: Each byte ends an integer; payloads are 0,3,2,2. Cumulative sums give 0,3,5,7. The high bit marks termination rather than contributing 128 to the number.
- An index contains only document IDs. Can enabling a position-request flag make phrase verification exact?
Answer: No. The positions were not stored. Rebuild with positions or inspect the original documents; the interface cannot supply missing evidence by itself.
Data structure and engine contract
The textbook explains postings, positional matching and gap encoding. The fixed Lucene API documents what a production iterator can expose and under which conditions. All text fragments and Python code here are original. The stored lists and codec deliberately omit the machinery needed for a durable search engine.
Make a prediction, then check
Does containing both words prove a document contains the exact phrase?
Learning objectives
- Distinguish document frequency, token positions, phrase matching and compressed document IDs.
- Run the original small corpus and explain a failure case.
Prerequisites & connections
Explore related knowledge →References
- An Introduction to Information Retrieval — online draft, April 1, 2009
Christopher D. Manning; Prabhakar Raghavan; Hinrich Schütze · 2009 - PostingsEnum — Lucene 9.12.3 core API
Apache Lucene contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author. Viewed physical PDF43/48/78/133/134/158/159/193; read PDF38/44/49/155/189/192 text. Inverted/positional indexes, Boolean merge, variable bytes, lexical vectors and evaluation; not a whole-book review. Read feature flags and freq/nextPosition/startOffset/endOffset definitions and call preconditions. No Java code or Lucene codec reproduced. 4 paired equations and four explained exercises. Postings checked against direct scans and phrase starts against sliding windows; repeated positions, live IDs, byte boundaries and gap reconstruction checked.
- Postings checked against direct scans and phrase starts against sliding windows; repeated positions, live IDs, byte boundaries and gap reconstruction checked.
- Four computed SVG variants per topic;10 numeric/geometry tests and30 responsive cases passed. Ten selected final captures directly viewed. Full article acceptance recorded separately.
Source locations checked:
- An Introduction to Information Retrieval — online draft, April 1, 2009 · Viewed physical PDF43/48/78/133/134/158/159/193; read PDF38/44/49/155/189/192 text. Inverted/positional indexes, Boolean merge, variable bytes, lexical vectors and evaluation; not a whole-book review.
- PostingsEnum — Lucene 9.12.3 core API · Read feature flags and freq/nextPosition/startOffset/endOffset definitions and call preconditions. No Java code or Lucene codec reproduced.
Related topics