Algorithm Search⌘K

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
Properties
not concurrentnot externalnot persistent

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 O(1+log⁡g)O(1 + \log g) comparisons when it skips gg 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 tt over a collection with document ids from a totally ordered set holds a sequence of postings (d0,f0),(d1,f1),…,(dn−1,fn−1)(d_0, f_0), (d_1, f_1), \ldots, (d_{n-1}, f_{n-1}), where d0<d1<⋯<dn−1d_0 < d_1 < \cdots < d_{n-1} are the ids of the documents that contain tt and fi≥1f_i \ge 1 is the number of times tt occurs in did_i. The length nn is the document frequency dft\mathrm{df}_t of the term. The operations are:

  • APPEND(P,d,f)(P, d, f): add the posting (d,f)(d, f) at the end, if dd is greater than the last id.
  • ACCESS(P,i)(P, i): return the posting at index ii.
  • NEXT-GEQ(P,x,lo)(P, x, lo): return the least index p≥lop \ge lo with dp≥xd_p \ge x, or nn 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 tt in did_i to each posting.

Representation

The plain form is two arrays of length nn: one for the ids and one for the frequencies. The arrays grow at the end, as a dynamic array does, so APPEND is amortized O(1)O(1). 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 di−di−1d_i - d_{i-1}, 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 2+log⁡2(u/n)2 + \log_2(u/n) bits each, for ids below uu, 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 lo,lo+1,lo+3,lo+7,…lo, lo + 1, lo + 3, lo + 7, \ldots, at offsets 2i−12^i - 1, until it finds an id at least xx or passes the end, then does a binary search in the last gap.

  1. APPEND(P, d, f) ▷ P.ids is strictly increasing
  2. 1if |P| > 0 and not (P.ids[|P| - 1] < d) then error "out of order"
  3. 2add d at the end of P.ids, add f at the end of P.tf
  4. NEXT-GEQ(P, x, lo) ▷ least p ≥ lo with P.ids[p] ≥ x, else |P|
  5. 3n ← |P|
  6. 4if lo ≥ n or not (P.ids[lo] < x) then return lo
  7. 5b ← 1 ▷ P.ids[lo + b - 1] < x
  8. 6while lo + 2b - 1 < n and P.ids[lo + 2b - 1] < x do b ← 2b
  9. 7a ← lo + b, c ← min(lo + 2b - 1, n)
  10. 8while a < c do ▷ P.ids[a - 1] < x, and c = n or P.ids[c] ≥ x
  11. 9q ← ⌊(a + c) / 2⌋
  12. 10if P.ids[q] < x then a ← q + 1 else c ← q
  13. 11return a

ACCESS(P,i)(P, i) returns (P.ids[i],P.tf[i])(P.\mathit{ids}[i], P.\mathit{tf}[i]). 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 (2,2)(2, 2). The token "sort" is a different term from "sorted", because the collection has no stemming.

Run NEXT-GEQ on the list of "sorted", with x=5x = 5 and lo=0lo = 0:

line probe id result state
L4 0 1 1<51 < 5 go on
L5 b=1b = 1
L6 1 2 2<52 < 5 b=2b = 2
L6 3 8 8≥58 \ge 5 stop the loop
L7 a=2a = 2, c=3c = 3
L9, L10 2 4 4<54 < 5 a=3a = 3
L11 return 3

The answer is index 3, the id 8. The call skips g=3g = 3 postings and makes 4 comparisons, which is the bound 2⌊log⁡23⌋+2=42 \lfloor \log_2 3 \rfloor + 2 = 4 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 P.ids[lo+b−1]<xP.\mathit{ids}[lo + b - 1] < x with bb a power of 2. When it stops, the answer lies between lo+blo + b and min⁡(lo+2b−1,n)\min(lo + 2b - 1, n), 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 xx 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 PP for a posting list with n=∣P∣n = |P| entries and P[i]P[i] for its ii-th document id, with 0≤i<n0 \le i < n. The invariant of the structure is

(I) P[0]<P[1]<⋯<P[n−1]P[0] < P[1] < \cdots < P[n-1], and P.tfP.\mathit{tf} has nn entries, each at least 1.

Lemma 1 (APPEND). If (I) holds before APPEND(P,d,f)(P, d, f) with f≥1f \ge 1, then the call either reports an error and changes nothing, or it adds (d,f)(d, f) at the end, and (I) holds after it.

Proof. If n>0n > 0 and d≤P[n−1]d \le P[n-1], line L1 reports an error before any change. Otherwise n=0n = 0, or P[n−1]<dP[n-1] < d. Line L2 adds dd at index nn and ff at the end of P.tfP.\mathit{tf}. The ids P[0…n−1]P[0 \ldots n-1] do not change, so they are still strictly increasing, and P[n−1]<P[n]=dP[n-1] < P[n] = d. Both arrays now have n+1n + 1 entries. □\square

ACCESS reads index ii of the two arrays and changes nothing, so it keeps (I).

Lemma 2 (binary search). Let a≤ca \le c be indices such that P[a−1]<xP[a-1] < x when a>0a > 0, and P[c]≥xP[c] \ge x when c<nc < n. The loop of lines L8 to L10 ends with a=c=pa = c = p, where pp is the least index with p≥ap \ge a and P[p]≥xP[p] \ge x, or p=np = n if there is none. It makes at most ⌈log⁡2(s+1)⌉\lceil \log_2(s+1) \rceil comparisons, where s=c−as = c - a is the start size.

Proof. Under (I), the indices q≥aq \ge a with P[q]<xP[q] < x form a prefix of the range, so pp is in [a,c][a, c] as long as the two conditions hold. Line L9 picks qq with a≤q<ca \le q < c. If P[q]<xP[q] < x, the new a=q+1a = q + 1 has P[a−1]<xP[a-1] < x. Else P[q]≥xP[q] \ge x, and the new c=qc = q has P[c]≥xP[c] \ge x. So both conditions hold after each step, and pp stays in [a,c][a, c]. When a=ca = c, the range has one index, so a=pa = p. Let s=c−as = c - a and q=a+⌊s/2⌋q = a + \lfloor s/2 \rfloor. The new size is ⌊s/2⌋\lfloor s/2 \rfloor in the second case, and s−⌊s/2⌋−1=⌈s/2⌉−1≤⌊s/2⌋s - \lfloor s/2 \rfloor - 1 = \lceil s/2 \rceil - 1 \le \lfloor s/2 \rfloor in the first case. So each step makes one comparison and at least halves the size, rounding down. From s≥1s \ge 1, the size reaches 0 after at most ⌊log⁡2s⌋+1=⌈log⁡2(s+1)⌉\lfloor \log_2 s \rfloor + 1 = \lceil \log_2(s+1) \rceil steps. □\square

Theorem (NEXT-GEQ). Assume (I) and lo≥0lo \ge 0. NEXT-GEQ(P,x,lo)(P, x, lo) returns the least index p≥lop \ge lo with P[p]≥xP[p] \ge x, or nn if there is none. Let g=p−log = p - lo when lo<nlo < n. The call makes one comparison when g=0g = 0, and at most 2⌊log⁡2g⌋+22 \lfloor \log_2 g \rfloor + 2 comparisons when g≥1g \ge 1. It makes no comparison when lo≥nlo \ge n.

Proof. If lo≥nlo \ge n, there is no index pp with lo≤p<nlo \le p < n, and line L4 returns lolo with no comparison. (The answer "none" is then lolo itself, which the caller reads as the end of the list.) If lo<nlo < n and P[lo]≥xP[lo] \ge x, line L4 returns lolo, which is the least such index, after one comparison. So g=0g = 0 costs one comparison.

Else P[lo]<xP[lo] < x. Line L5 sets b=1b = 1, so the statement

(G) bb is a power of 2 and P[lo+b−1]<xP[lo + b - 1] < x

holds. A step of the loop of line L6 runs only when P[lo+2b−1]<xP[lo + 2b - 1] < x, and then doubles bb, so (G) holds after it. Each step at least doubles bb and lo+2b−1<nlo + 2b - 1 < n is needed for a step, so the loop stops. When it stops, either lo+2b−1≥nlo + 2b - 1 \ge n or P[lo+2b−1]≥xP[lo + 2b - 1] \ge x. Line L7 sets a=lo+ba = lo + b and c=min⁡(lo+2b−1,n)c = \min(lo + 2b - 1, n). By (G), P[a−1]<xP[a - 1] < x. By the stop condition, c=nc = n or P[c]≥xP[c] \ge x. And a≤ca \le c, because lo+b≤lo+2b−1lo + b \le lo + 2b - 1 and lo+b−1<nlo + b - 1 < n by (G). So Lemma 2 applies, and line L11 returns the least p≥ap \ge a with P[p]≥xP[p] \ge x, or nn. Each index from lolo to a−1a - 1 holds an id of at most P[a−1]<xP[a-1] < x by (I), so this pp is also the least p≥lop \ge lo with P[p]≥xP[p] \ge x.

For the count, let b=2tb = 2^t at the end of the loop, so the loop made tt steps that each made one comparison with result "<<". The test of line L6 that ends the loop makes one more comparison, unless lo+2b−1≥nlo + 2b - 1 \ge n. By (G), P[lo+2t−1]<xP[lo + 2^t - 1] < x, so p≥lo+2tp \ge lo + 2^t and g≥2tg \ge 2^t, that is t≤⌊log⁡2g⌋t \le \lfloor \log_2 g \rfloor. The binary search starts with size c−a≤(lo+2b−1)−(lo+b)=2t−1c - a \le (lo + 2b - 1) - (lo + b) = 2^t - 1, so by Lemma 2 it makes at most ⌈log⁡22t⌉=t\lceil \log_2 2^t \rceil = t comparisons. The total is at most 1+t+1+t=2t+2≤2⌊log⁡2g⌋+21 + t + 1 + t = 2t + 2 \le 2 \lfloor \log_2 g \rfloor + 2, where the first 1 is line L4. ■\blacksquare

Consequence. A sequence of calls NEXT-GEQ(P,xj,pj−1)(P, x_j, p_{j-1}), where each call starts at the answer pj−1p_{j-1} of the call before it, with rr calls and ∑jgj≤n\sum_j g_j \le n, makes at most ∑j(2log⁡2(gj+1)+2)≤2rlog⁡2(1+n/r)+2r\sum_j (2 \log_2(g_j + 1) + 2) \le 2r \log_2(1 + n/r) + 2r comparisons. The first step uses ⌊log⁡2g⌋≤log⁡2(g+1)\lfloor \log_2 g \rfloor \le \log_2(g + 1) for g≥1g \ge 1 and 1≤21 \le 2 for g=0g = 0. The second step uses that log⁡2(1+y)\log_2(1 + y) is concave, so by Jensen's inequality the sum of log⁡2(1+gj)\log_2(1 + g_j) is at most rlog⁡2(1+1r∑jgj)r \log_2(1 + \frac{1}{r} \sum_j g_j).

Complexity

  • APPEND: O(1)O(1) amortized time, and one comparison.
  • ACCESS: O(1)O(1) time.
  • NEXT-GEQ: let pp be the answer and g=p−log = p - lo. The call makes 1 comparison when g=0g = 0, and at most 2⌊log⁡2g⌋+22 \lfloor \log_2 g \rfloor + 2 comparisons when g≥1g \ge 1, so the time is O(1+log⁡g)O(1 + \log g). A plain binary search over the rest of the list would cost about log⁡2(n−lo)\log_2(n - lo) comparisons, even when the answer is near lolo.
  • A sequence of rr calls in which each call starts at the answer of the call before it skips at most nn postings in total, and makes at most 2rlog⁡2(1+n/r)+2r2r \log_2(1 + n/r) + 2r comparisons by the concavity of the logarithm. This is the bound that the galloping intersections, such as small-versus-small, rely on.
  • Build: O(T)O(T) expected time for TT tokens, with a hash table from terms to lists.
  • Space: Θ(n)\Theta(n) words for one list, and a number of words linear in the total number of postings for all lists. That total is at most TT.

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 f=2f = 2, not two postings with the same id. The test in line L1 is a strict <<; with ≤\le it would accept a duplicate.
  • Binary search from index 0. A call NEXT-GEQ(P,x,0)(P, x, 0) in each step of an intersection, in place of NEXT-GEQ(P,x,p)(P, x, p) from the last answer pp, makes the cost of each step about log⁡2n\log_2 n and loses the bound of 2rlog⁡2(1+n/r)+2r2r \log_2(1 + n/r) + 2r.
  • Overshoot of the galloping probe. Line L6 must test lo+2b−1<nlo + 2b - 1 < n before it reads the id. Line L7 must cap cc at nn, 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.

irtoy.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.access
  • a full proof of time.append
  • a full proof of time.build
  • a full proof of time.next_geq
  • a full proof of space.total
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/CHQP94/text.yaml