Data structureintro
Posting list
Also called postings list.
The sorted list of document ids, with optional frequencies and positions, for one term of an inverted index.
- Time
- O(1) accessO(1) amortized appendO(T) expected buildO(1 + log g) next_geq
- Space
- Θ(n) total
- Where
- T = the number of tokens in the collection; g = the number of postings that one NEXT-GEQ call skips; n = the number of postings in the list
- Model
- Word RAM
- Properties
- not concurrentnot externalnot persistent
- Evidence
- Proof sketchCode in 1 languages
A posting list is the list of documents that contain one term, kept in increasing order of document id, with an optional term frequency and list of positions for each document. One posting list for each term of the vocabulary, plus a dictionary that maps a term to its list, makes an inverted index. The list is the row of the term-document incidence matrix for that term, stored without its zeros. Because the ids are sorted, two lists can be intersected by a merge, and a search for the first id at least some value takes comparisons when it skips entries.
In plain words
Think of the index at the back of a book. For each word it gives the pages where the word appears, from the first page to the last. A posting list is the same thing for a search engine: for each word, the numbers of the documents that hold the word, from small to large. Each entry is called a posting. It can also say how many times the word occurs in that document, and where.
The order is the important part. Because the numbers go up, the engine can walk two lists side by side to find the documents that hold both words. It can also jump ahead in a list to the first number past some value, without a look at each entry on the way.
The abstract type
A posting list for a term over a collection with document ids from a totally ordered set holds a sequence of postings , where are the ids of the documents that contain and is the number of times occurs in . The length is the document frequency of the term. The operations are:
- APPEND: add the posting at the end, if is greater than the last id.
- ACCESS: return the posting at index .
- NEXT-GEQ: return the least index with , or if there is none.
NEXT-GEQ is the operation that intersection algorithms need. It is called next in the interface of Buettcher, Clarke and Cormack, and nextGEQ in many engines. A positional index adds the list of positions of in to each posting.
Representation
The plain form is two arrays of length : one for the ids and one for the frequencies. The arrays grow at the end, as a dynamic array does, so APPEND is amortized . An index is built in order of document id, so each new posting goes at the end of its list.
In a real engine the ids are stored as gaps , which are small for long lists, and the gaps are compressed with a code such as variable-byte encoding or PForDelta. This is postings gap encoding. A compressed list must be decoded from the start, so engines add skip pointers or cut the list into blocks with the first id of each block in a small table. Elias-Fano encoding stores the ids in about bits each, for ids below , and still supports NEXT-GEQ directly. This page uses the plain arrays.
Operations
The main operations are APPEND and NEXT-GEQ. NEXT-GEQ is a galloping search, the form of exponential search that starts at a given index. It probes the indices , at offsets , until it finds an id at least or passes the end, then does a binary search in the last gap.
APPEND(P, d, f) ▷ P.ids is strictly increasing- 1
if |P| > 0 and not (P.ids[|P| - 1] < d) then error "out of order" - 2
add d at the end of P.ids, add f at the end of P.tf NEXT-GEQ(P, x, lo) ▷ least p ≥ lo with P.ids[p] ≥ x, else |P|- 3
n ← |P| - 4
if lo ≥ n or not (P.ids[lo] < x) then return lo - 5
b ← 1 ▷ P.ids[lo + b - 1] < x - 6
while lo + 2b - 1 < n and P.ids[lo + 2b - 1] < x do b ← 2b - 7
a ← lo + b, c ← min(lo + 2b - 1, n) - 8
while a < c do ▷ P.ids[a - 1] < x, and c = n or P.ids[c] ≥ x - 9
q ← ⌊(a + c) / 2⌋ - 10
if P.ids[q] < x then a ← q + 1 else c ← q - 11
return a
ACCESS returns . To build all lists of a collection, read the documents in increasing id order, count the terms of each document in a hash table, and call APPEND on the list of each distinct term.
Example
The toy collection of the information retrieval pages has 8 documents, 79 tokens, 50 distinct terms and 74 postings. Of the 50 lists, 35 have only one posting. The longest lists are:
| term | ids | tf |
|---|---|---|
| a | 1, 3, 4, 6, 7 | 2, 1, 2, 2, 1 |
| sorted | 1, 2, 4, 8 | 1, 2, 1, 1 |
| array | 1, 2, 8 | 1, 1, 1 |
| posting | 3, 4, 5 | 1, 1, 1 |
Document 2 is "merge sort merges two sorted runs into one sorted array", so the posting of "sorted" for it is . The token "sort" is a different term from "sorted", because the collection has no stemming.
Run NEXT-GEQ on the list of "sorted", with and :
| line | probe | id | result | state |
|---|---|---|---|---|
| L4 | 0 | 1 | go on | |
| L5 | ||||
| L6 | 1 | 2 | ||
| L6 | 3 | 8 | stop the loop | |
| L7 | , | |||
| L9, L10 | 2 | 4 | ||
| L11 | return 3 |
The answer is index 3, the id 8. The call skips postings and makes 4 comparisons, which is the bound of the next section.
Correctness
The invariant of the structure is that the ids are strictly increasing and each frequency is at least 1. Line L1 rejects an id that would break the order, so APPEND keeps the invariant. For NEXT-GEQ, the loop of line L6 keeps with a power of 2. When it stops, the answer lies between and , and the binary search of lines L8 to L10 keeps the condition in the comment of line L8 until the range has one index. Because the ids are sorted, the indices with an id below form a prefix, so the first index past that prefix is the answer. The full proof, with the count of comparisons, is in the proof file below.
Proof: The posting list operations keep the order and NEXT-GEQ finds the first id at least xfull
We write for a posting list with entries and for its -th document id, with . The invariant of the structure is
(I) , and has entries, each at least 1.
Lemma 1 (APPEND). If (I) holds before APPEND with , then the call either reports an error and changes nothing, or it adds at the end, and (I) holds after it.
Proof. If and , line L1 reports an error before any change. Otherwise , or . Line L2 adds at index and at the end of . The ids do not change, so they are still strictly increasing, and . Both arrays now have entries.
ACCESS reads index of the two arrays and changes nothing, so it keeps (I).
Lemma 2 (binary search). Let be indices such that when , and when . The loop of lines L8 to L10 ends with , where is the least index with and , or if there is none. It makes at most comparisons, where is the start size.
Proof. Under (I), the indices with form a prefix of the range, so is in as long as the two conditions hold. Line L9 picks with . If , the new has . Else , and the new has . So both conditions hold after each step, and stays in . When , the range has one index, so . Let and . The new size is in the second case, and in the first case. So each step makes one comparison and at least halves the size, rounding down. From , the size reaches 0 after at most steps.
Theorem (NEXT-GEQ). Assume (I) and . NEXT-GEQ returns the least index with , or if there is none. Let when . The call makes one comparison when , and at most comparisons when . It makes no comparison when .
Proof. If , there is no index with , and line L4 returns with no comparison. (The answer "none" is then itself, which the caller reads as the end of the list.) If and , line L4 returns , which is the least such index, after one comparison. So costs one comparison.
Else . Line L5 sets , so the statement
(G) is a power of 2 and
holds. A step of the loop of line L6 runs only when , and then doubles , so (G) holds after it. Each step at least doubles and is needed for a step, so the loop stops. When it stops, either or . Line L7 sets and . By (G), . By the stop condition, or . And , because and by (G). So Lemma 2 applies, and line L11 returns the least with , or . Each index from to holds an id of at most by (I), so this is also the least with .
For the count, let at the end of the loop, so the loop made steps that each made one comparison with result "". The test of line L6 that ends the loop makes one more comparison, unless . By (G), , so and , that is . The binary search starts with size , so by Lemma 2 it makes at most comparisons. The total is at most , where the first 1 is line L4.
Consequence. A sequence of calls NEXT-GEQ, where each call starts at the answer of the call before it, with calls and , makes at most comparisons. The first step uses for and for . The second step uses that is concave, so by Jensen's inequality the sum of is at most .
Complexity
- APPEND: amortized time, and one comparison.
- ACCESS: time.
- NEXT-GEQ: let be the answer and . The call makes 1 comparison when , and at most comparisons when , so the time is . A plain binary search over the rest of the list would cost about comparisons, even when the answer is near .
- A sequence of calls in which each call starts at the answer of the call before it skips at most postings in total, and makes at most comparisons by the concavity of the logarithm. This is the bound that the galloping intersections, such as small-versus-small, rely on.
- Build: expected time for tokens, with a hash table from terms to lists.
- Space: words for one list, and a number of words linear in the total number of postings for all lists. That total is at most .
Variants
- Document ids only. For Boolean queries alone, the frequencies are not needed, and the list is one sorted array of ids.
- With positions. Each posting holds the sorted list of the positions of the term in the document. This is the positional index, which answers phrase queries.
- Compressed lists. Gaps with a variable-length code, or Elias-Fano encoding, cut the space to a few bits for each posting.
- Blocked lists with skips. The list is cut into blocks of about 64 or 128 postings, and a table holds the first id of each block, so NEXT-GEQ decodes only one block. Skip pointers are the textbook form of this idea.
- Impact-ordered lists. For ranked retrieval, some engines sort the postings by a score instead of by id, which helps early stop but breaks the merge.
When to use it
Use a posting list for each term whenever a collection is searched by words: it is the core of every inverted index. Use the plain array form for small or in-memory indexes and for the results of an intersection, and a compressed form with blocks for large indexes. For a term that occurs in almost every document, a bit vector over all ids can be smaller and faster than a list of ids.
Pitfalls
- Ids out of order. If documents are added in a random order, a plain append breaks the sort, and each merge then gives wrong answers. Line L1 must test the order; a list that is not built in id order must be sorted before use.
- Duplicate ids. A term that occurs twice in one document must give one posting with , not two postings with the same id. The test in line L1 is a strict ; with it would accept a duplicate.
- Binary search from index 0. A call NEXT-GEQ in each step of an intersection, in place of NEXT-GEQ from the last answer , makes the cost of each step about and loses the bound of .
- Overshoot of the galloping probe. Line L6 must test before it reads the id. Line L7 must cap at , else the binary search reads past the end.
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
# 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
posting_list.py 75 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/posting-list/. The authors are listed in prov/CHQP94.jsonl.
from typing import Any
class PostingList:
"""The posting list of one term: strictly increasing document ids, each with its term frequency.
The ids may be any values with a total order that support < and ==.
Space is two arrays of len(self) entries.
"""
def __init__(self) -> None:
self.ids: list[Any] = []
self.tf: list[int] = []
def __len__(self) -> int:
return len(self.ids)
def append(self, doc_id: Any, tf: int = 1) -> None:
"""Add a posting at the end. Precondition: doc_id is greater than the last id. Cost O(1) amortized."""
if self.ids and not (self.ids[-1] < doc_id): # @line L1
raise ValueError("document ids must be appended in increasing order")
self.ids.append(doc_id) # @line L2
self.tf.append(tf)
def access(self, i: int) -> tuple[Any, int]:
"""Return the posting at index i as (doc_id, tf). Precondition: 0 <= i < len(self). Cost O(1)."""
return self.ids[i], self.tf[i]
def next_geq(self, x: Any, lo: int = 0) -> int:
"""Return the least index p >= lo with ids[p] >= x, or len(self) if there is none.
Galloping search from lo. Precondition: 0 <= lo. If g = p - lo, the call makes
one comparison when g = 0, and at most 2 floor(log2 g) + 2 comparisons when g >= 1.
"""
ids = self.ids
n = len(ids) # @line L3
if lo >= n or not (ids[lo] < x): # @line L4
return lo
b = 1 # @line L5: ids[lo + b - 1] < x
while lo + 2 * b - 1 < n and ids[lo + 2 * b - 1] < x: # @line L6
b *= 2
a, c = lo + b, min(lo + 2 * b - 1, n) # @line L7
while a < c: # @line L8
q = (a + c) // 2 # @line L9
if ids[q] < x: # @line L10
a = q + 1
else:
c = q
return a # @line L11
def check_invariant(self) -> None:
"""Raise AssertionError unless the ids are strictly increasing and each tf is positive."""
assert len(self.ids) == len(self.tf)
for i in range(1, len(self.ids)):
assert self.ids[i - 1] < self.ids[i]
assert all(f >= 1 for f in self.tf)
def build_postings(docs: dict[int, list[str]]) -> dict[str, PostingList]:
"""Build the posting list of each term of a tokenized collection.
The documents are read in increasing id order, so each append keeps the order.
Cost O(T) expected time for T tokens, with a hash table from terms to lists.
"""
index: dict[str, PostingList] = {}
for d in sorted(docs):
counts: dict[str, int] = {}
for term in docs[d]:
counts[term] = counts.get(term, 0) + 1
for term, f in counts.items():
index.setdefault(term, PostingList()).append(d, f)
return index
test_posting_list.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/posting-list/. The authors are listed in prov/CHQP94.jsonl.
import bisect
import math
import random
import irtoy
from posting_list import PostingList, build_postings
class Counter:
def __init__(self) -> None:
self.n = 0
class Key:
"""An integer that counts each comparison it takes part in."""
def __init__(self, v: int, c: Counter) -> None:
self.v, self.c = v, c
def __lt__(self, other: "Key") -> bool:
self.c.n += 1
return self.v < other.v
def __eq__(self, other: object) -> bool:
assert isinstance(other, Key)
self.c.n += 1
return self.v == other.v
def __hash__(self) -> int:
return hash(self.v)
def make(ids: list[int]) -> PostingList:
p = PostingList()
for d in ids:
p.append(d)
return p
def test_example() -> None:
index = build_postings({d: irtoy.tokenize(t) for d, t in irtoy.DOCS.items()})
p = index["sorted"]
assert p.ids == [1, 2, 4, 8]
assert p.tf == [1, 2, 1, 1]
assert p.access(1) == (2, 2)
c = Counter()
q = PostingList()
for d in p.ids:
q.append(Key(d, c))
c.n = 0
assert q.next_geq(Key(5, c), 0) == 3
assert c.n == 4
assert p.next_geq(4, 0) == 2
assert p.next_geq(9, 0) == 4
assert p.next_geq(1, 2) == 2
def test_irtoy_statistics() -> None:
index = build_postings({d: irtoy.tokenize(t) for d, t in irtoy.DOCS.items()})
assert len(index) == 50
assert sum(len(p) for p in index.values()) == 74
for term, p in index.items():
p.check_invariant()
assert len(p) == irtoy.df(term)
assert sum(p.tf) == irtoy.cf(term)
for d, f in zip(p.ids, p.tf):
assert f == irtoy.tf(term, d)
def test_edges() -> None:
p = PostingList()
assert len(p) == 0
assert p.next_geq(5) == 0
p.check_invariant()
p.append(3, 2)
assert p.next_geq(3) == 0 and p.next_geq(4) == 1 and p.next_geq(4, 1) == 1
for bad in (3, 1):
try:
p.append(bad)
except ValueError:
pass
else:
raise AssertionError("append out of order was accepted")
p.check_invariant()
def test_random_against_bisect() -> None:
rng = random.Random(20261115)
for _ in range(800):
n = rng.randint(0, 60)
ids = sorted(rng.sample(range(200), n))
c = Counter()
p = make([Key(d, c) for d in ids])
p.check_invariant()
for _ in range(5):
lo = rng.randint(0, n + 1)
x = rng.randint(-5, 205)
c.n = 0
got = p.next_geq(Key(x, c), lo)
want = max(lo, bisect.bisect_left(ids, x)) if lo <= n else lo
assert got == want
g = got - lo
if lo < n:
bound = 1 if g == 0 else 2 * math.floor(math.log2(g)) + 2
assert c.n <= bound
else:
assert c.n == 0
History
Inverted files with sorted lists of record numbers are among the oldest structures of text retrieval. The books of Witten, Moffat and Bell and the survey of Zobel and Moffat describe the modern layout: document ids in increasing order, gaps between ids compressed with a variable-length code, and in-document frequencies and positions stored next to the ids. Manning, Raghavan and Schuetze use the name "postings list" in their textbook, and Buettcher, Clarke and Cormack define the interface with first, last, next and prev.
References
- Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 1, Section 1.2 (building an inverted index, the dictionary and the postings sorted by document id), and Chapter 2, Section 2.3 (skip pointers)
- Stefan Buettcher, Charles L. A. Clarke and Gordon V. Cormack, Information Retrieval, Implementing and Evaluating Search Engines, MIT Press, 2010, Chapter 2, Section 2.1 (the inverted index interface first, last, next and prev, and Section 2.1.2 on the implementation of these methods)
- Justin Zobel and Alistair Moffat, Inverted files for text search engines, ACM Computing Surveys 38(2), Article 6, 2006, the layout of an inverted list as document ids with in-document frequencies and positions, and its compression
- Ian H. Witten, Alistair Moffat and Timothy C. Bell, Managing Gigabytes, second edition, Morgan Kaufmann, 1999, Chapter 3 (indexing) and Chapter 4 (querying)
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 | W4 complete |
|
Tag CHQP94 Edit this page History Report an error Markdown