Algorithm Search⌘K

Data structurecore

Positional index

Also called positional inverted index.

An inverted index whose postings store, for each document, the positions where the term occurs, so phrase and proximity queries can be answered.

Time
O(L) expected add_documentO(T) expected buildO(log f + g) positions
Space
Θ(T) total
Where
L = the number of tokens in one document; T = the number of tokens in the collection; f = the number of documents that hold the term; g = the number of times the term occurs in the document
Properties
not concurrentnot externalnot persistent

A positional index is an inverted index whose posting lists also record where each term occurs: for each document that holds the term, it stores the sorted list of the token positions of the term in that document. With these positions, a search engine can answer a phrase query such as "posting list", which needs the two words next to each other and in this order, and proximity queries such as "the two words within 3 words of each other". A plain index of document ids can only say that both words occur somewhere in the document. The cost is space: a positional index stores one entry for each token of the collection, so it grows with the length of the text, not with the number of distinct pairs of a term and a document.

In plain words

A plain index keeps, for each word, the list of documents that hold it. A positional index keeps a bit more: for each of those documents, the places in the text where the word stands, counted as the first word, the second word, and so on.

To check if a document holds the phrase "posting list", look up the places of "posting" and of "list" in that document. The phrase is there if some place of "list" is just one after a place of "posting".

So the index answers two kinds of questions: which documents hold a word, and where in each document the word is. The price is one stored number for each word of the text.

The abstract type

A positional index over a collection of documents, each a sequence of tokens, supports:

  • ADD-DOCUMENT(d,t0,…,tL−1)(d, t_0, \ldots, t_{L-1}): add a document with an id greater than all ids before.
  • POSTINGS(w)(w): the increasing ids of the documents that hold term ww.
  • POSITIONS(w,d)(w, d): the increasing positions ii with ti=wt_i = w in document dd, or the empty list.
  • ENTRIES(w)(w): the positional posting list of ww, the pairs (d,POSITIONS(w,d))(d, \mathrm{POSITIONS}(w, d)) in increasing order of dd, which is the input of positional intersection.
  • The statistics df(w)=∣POSTINGS(w)∣\mathrm{df}(w) = |\mathrm{POSTINGS}(w)|, tf(w,d)=∣POSITIONS(w,d)∣\mathrm{tf}(w, d) = |\mathrm{POSITIONS}(w, d)| and cf(w)\mathrm{cf}(w), the sum of tf(w,d)\mathrm{tf}(w, d) over all dd.

Positions count tokens from 0. They are word positions, not byte offsets.

Representation

A dictionary, here a hash table, maps each term to its positional list. The list is two parallel arrays: the increasing document ids, and for each id, the increasing array of positions. In the notation of Manning, Raghavan and Schuetze, the list of a term is written as entries ⟨d:p1,p2,…⟩\langle d: p_1, p_2, \ldots \rangle. On disk, both levels are usually coded as gaps with a gap code: the ids as gaps between ids, and the positions of each document as gaps that restart at the first position of the document.

Operations

  1. ADD-DOCUMENT(I, d, t_0, ..., t_{L-1}) ▷ d greater than every id in I
  2. 1if I has a document and not (the last id < d) then error "out of order"
  3. 2for i ← 0 to L - 1 do
  4. 3P ← the positional list of t_i, made empty if t_i is new ▷ hash table
  5. 4if P is empty or the last id of P ≠ d then append (d, ()) to P
  6. 5append i to the positions of the last entry of P
  7. POSITIONS(I, w, d)
  8. 6if w has no list then return ()
  9. 7p ← the least index with p = |P.ids| or P.ids[p] ≥ d ▷ binary search
  10. 8if p < |P.ids| and P.ids[p] = d then return P.pos[p]
  11. 9return ()

The tokens of one document come in order of position, so line L5 always appends a position greater than the ones already in the list. The documents come in order of id, so line L4 appends an id greater than the ones already there. POSTINGS and ENTRIES return the stored arrays.

Example

On the toy collection, 8 documents with 79 tokens and 50 distinct terms, the positional lists of three terms are:

term df positional list
sorted 4 ⟨1:7⟩\langle 1: 7 \rangle, ⟨2:4,8⟩\langle 2: 4, 8 \rangle, ⟨4:5⟩\langle 4: 5 \rangle, ⟨8:1⟩\langle 8: 1 \rangle
posting 3 ⟨3:8⟩\langle 3: 8 \rangle, ⟨4:1⟩\langle 4: 1 \rangle, ⟨5:8⟩\langle 5: 8 \rangle
list 2 ⟨3:9⟩\langle 3: 9 \rangle, ⟨4:2,6⟩\langle 4: 2, 6 \rangle

Document 2 is "merge sort merges two sorted runs into one sorted array", so "sorted" stands at positions 4 and 8, and tf(sorted,2)=2\mathrm{tf}(\text{sorted}, 2) = 2.

The phrase "posting list" is in a document when a position of "list" is one more than a position of "posting". The common documents of the two lists are 3 and 4. In document 3, 8+1=98 + 1 = 9 is a position of "list", and in document 4, 1+1=21 + 1 = 2 is. Document 5 holds "posting" at position 8 but not "list": its word is "lists", a different token. So the phrase is in documents 3 and 4. The query "list sorted" shows what the positions add: both words are in document 4, at positions 2, 6 and 5, but no position of "sorted" is one more than a position of "list", so the phrase is in no document, while the AND query returns document 4.

The whole index holds 74 document ids and 79 positions, one for each token. The index without positions holds only the 74 ids.

Correctness

The proof keeps one invariant after each document: for each term, the stored ids are exactly the documents so far that hold it, in increasing order, and the positions stored with each id are exactly its positions in that document, in increasing order. ADD-DOCUMENT keeps it, because the new id is greater than all ids before and the tokens come in order of position, so each append goes at the right end. POSITIONS is a binary search on the ids. The full proof is in the proof file below.

Proof: The positional index stores, for each term, exactly its documents and its positions, in orderfull

The collection is a sequence of documents d1<d2<⋯<dNd_1 < d_2 < \cdots < d_N added in this order, and document dd is the token sequence t0d,…,tLd−1dt^d_0, \ldots, t^d_{L_d - 1}. For a term ww, let D(w)=(d:w occurs in d)D(w) = (d : w \text{ occurs in } d) in increasing order, and for a document dd let Pos(w,d)=(i:tid=w)\mathrm{Pos}(w, d) = (i : t^d_i = w) in increasing order. The index stores, for each term ww that it has seen, an array ids(w)ids(w) and an array pos(w)pos(w) of the same length.

Invariant (P). After the first jj documents are added, for every term ww: ids(w)ids(w) is D(w)D(w) restricted to d1,…,djd_1, \ldots, d_j, and pos(w)[p]=Pos(w,ids(w)[p])pos(w)[p] = \mathrm{Pos}(w, ids(w)[p]) for each index pp. A term with no occurrence in these documents has no entry.

Lemma 1. ADD-DOCUMENT keeps (P), and it raises an error, with no change to the lists, if the new id is not greater than the last one.

Proof. Line L1 checks the order before any change. Let d=dj+1d = d_{j+1} be greater than every id added before, and let (P) hold for the first jj documents. We show by induction on ii that after the token tidt^d_i is handled, for every term ww:

  • if ww occurs in t0d,…,tidt^d_0, \ldots, t^d_i, then ids(w)ids(w) is D(w)D(w) restricted to d1,…,djd_1, \ldots, d_j, followed by dd, and the last entry of pos(w)pos(w) is (i′≤i:ti′d=w)(i' \le i : t^d_{i'} = w);
  • else ids(w)ids(w) and pos(w)pos(w) are as before the call.

Before the first token, the second case holds for every term. Let w=tidw = t^d_i. Line L3 finds or creates the lists of ww. If ww did not occur in t0d,…,ti−1dt^d_0, \ldots, t^d_{i-1}, then the last id of ids(w)ids(w), if there is one, is an earlier document, so it is less than dd and not equal to it. Line L4 appends dd with an empty position list, and line L5 appends ii, which gives the list (i)(i). If ww did occur, the last id is dd, line L4 does nothing, and line L5 appends ii to the last position list. Since ii is greater than every position of that list, the list stays increasing and equals (i′≤i:ti′d=w)(i' \le i : t^d_{i'} = w). Other terms do not change.

After the last token, every term of dd has dd appended once, at the end, with the full position list Pos(w,d)\mathrm{Pos}(w, d). Since dd is greater than every earlier id, ids(w)ids(w) stays strictly increasing and is D(w)D(w) restricted to d1,…,dj+1d_1, \ldots, d_{j+1}. Terms that do not occur in dd do not change. So (P) holds for j+1j + 1 documents. □\square

Lemma 2. POSITIONS(w,d)(w, d) returns Pos(w,d)\mathrm{Pos}(w, d), which is the empty list when ww does not occur in dd.

Proof. If ww has no entry, then by (P) it occurs in no document, and line L6 returns the empty list. Else line L7 finds the least index pp with p=∣ids(w)∣p = |ids(w)| or ids(w)[p]≥dids(w)[p] \ge d, by binary search on the strictly increasing array ids(w)ids(w). If ids(w)[p]=dids(w)[p] = d, then d∈D(w)d \in D(w), and by (P) line L8 returns Pos(w,d)\mathrm{Pos}(w, d). Else dd is not in ids(w)ids(w), because every id before index pp is less than dd and every id from pp on is greater, so ww does not occur in dd and line L9 returns the empty list. □\square

Theorem. After the documents d1<⋯<dNd_1 < \cdots < d_N are added, POSTINGS(w)=D(w)(w) = D(w), POSITIONS(w,d)=Pos(w,d)(w, d) = \mathrm{Pos}(w, d), df(w)=∣D(w)∣\mathrm{df}(w) = |D(w)|, tf(w,d)=∣Pos(w,d)∣\mathrm{tf}(w, d) = |\mathrm{Pos}(w, d)| and cf(w)=∑d∣Pos(w,d)∣\mathrm{cf}(w) = \sum_d |\mathrm{Pos}(w, d)|.

Proof. (P) holds with no documents, because no term has an entry. By Lemma 1 and induction on jj, it holds after all NN documents. The claims on POSTINGS and on the counts follow from (P), and the claim on POSITIONS is Lemma 2. ■\blacksquare

Space. Each token tidt^d_i adds exactly one position, at line L5, and each pair of a term and a document that holds it adds exactly one id, at line L4. With T=∑dLdT = \sum_d L_d tokens, the index holds TT positions and at most TT ids, plus one dictionary entry for each distinct term, at most TT of them. So the space is Θ(T)\Theta(T) words for a collection with T≥1T \ge 1.

Time. Line L3 is one lookup in a hash table, O(1)O(1) expected, and lines L4 and L5 are O(1)O(1) amortized appends. So ADD-DOCUMENT costs O(Ld)O(L_d) expected, and the whole build costs O(T)O(T) expected. POSITIONS makes O(log⁡∣D(w)∣)O(\log |D(w)|) comparisons in line L7 and copies ∣Pos(w,d)∣|\mathrm{Pos}(w, d)| positions. ■\blacksquare

Complexity

  • Space. One position for each token and one id for each pair of a term and a document that holds it, so Θ(T)\Theta(T) words for TT tokens. A plain index stores only the ids, which can be much fewer than TT when words repeat in a document.
  • Build. ADD-DOCUMENT makes one hash lookup and O(1)O(1) amortized appends for each token, so O(L)O(L) expected time for a document of LL tokens and O(T)O(T) for the collection.
  • Lookup. POSITIONS makes O(log⁡f)O(\log f) comparisons on the ids of a term with ff documents, then returns its gg positions.
  • Queries. A phrase or proximity query of two terms costs the intersection of the document lists plus, in each common document, a merge of the two position lists; see positional intersection.

Variants

  • Biword index. Index each pair of consecutive words as one term. A two-word phrase is then one lookup, but longer phrases need several lookups and can give false matches, and the dictionary grows a lot.
  • A combined index. Keep a biword or phrase index for frequent phrases, and the positional index for the rest.
  • Index of positions in the collection. Number all tokens of the collection in one sequence, and store for each term the increasing list of its global positions. Buettcher, Clarke and Cormack build their index this way, with methods that find the next and the previous occurrence of a term from a given position.
  • Skips in position lists. Skip pointers on the document level let a query jump to the next common document before it reads any position.
  • Full-text indexes. A suffix array answers phrase queries of any length with no tokenizing, at a higher cost in space, and document listing reports the documents that hold a pattern.

When to use it

Use it when the engine must support phrase queries or rank documents by how close the query words are. If only the presence of words matters, a plain index of ids and frequencies is smaller and faster to scan.

Pitfalls

  • Positions that do not match the query tokens. The positions must be counted after the same tokenizing as the query. If the index drops stop words but keeps their places, or keeps them and the query drops them, phrase queries miss or find the wrong text.
  • Positions in the wrong order. Line L5 assumes the tokens come in order. An index built from several passes over a document must sort the positions of each entry.
  • Gaps across documents. On disk, the gaps of positions restart in each document. A gap from the last position of one document to the first of the next has no meaning.
  • Space. A positional index needs one entry per token. Plan the size by the length of the text, not by the number of distinct pairs of a term and a document.

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
positional_index.py 91 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/positional-index/. The authors are listed in prov/F109TQ.jsonl.

from bisect import bisect_left
from typing import Sequence


class PositionalIndex:
    """For each term, the strictly increasing ids of the documents that hold it, and for
    each such document the strictly increasing positions of the term in it.

    Positions count tokens from 0. Space is one entry per token plus one per posting.
    """

    def __init__(self) -> None:
        self._ids: dict[str, list[int]] = {}
        self._pos: dict[str, list[list[int]]] = {}
        self._last: int | None = None

    def add_document(self, doc_id: int, tokens: Sequence[str]) -> None:
        """Add a document. Precondition: doc_id is greater than every id added before.

        Cost O(len(tokens)) expected, with a hash table from terms to lists.
        """
        if self._last is not None and not (self._last < doc_id):  # @line L1
            raise ValueError("documents must be added in increasing id order")
        self._last = doc_id
        for i, term in enumerate(tokens):  # @line L2
            ids = self._ids.setdefault(term, [])  # @line L3
            pos = self._pos.setdefault(term, [])
            if not ids or ids[-1] != doc_id:  # @line L4
                ids.append(doc_id)
                pos.append([])
            pos[-1].append(i)  # @line L5

    def postings(self, term: str) -> list[int]:
        """Return the ids of the documents that hold term, in increasing order."""
        return list(self._ids.get(term, []))

    def entries(self, term: str) -> list[tuple[int, list[int]]]:
        """Return the positional posting list of term as (doc_id, positions) pairs."""
        return [(d, list(p)) for d, p in zip(self._ids.get(term, []), self._pos.get(term, []))]

    def positions(self, term: str, doc_id: int) -> list[int]:
        """Return the positions of term in document doc_id, or [] if it does not occur.

        Cost O(log df(term)) by binary search on the ids, plus the length of the answer.
        """
        ids = self._ids.get(term)  # @line L6
        if ids is None:
            return []
        p = bisect_left(ids, doc_id)  # @line L7
        if p < len(ids) and ids[p] == doc_id:  # @line L8
            return list(self._pos[term][p])
        return []  # @line L9

    def df(self, term: str) -> int:
        """Return the number of documents that hold term."""
        return len(self._ids.get(term, []))

    def tf(self, term: str, doc_id: int) -> int:
        """Return the number of times term occurs in document doc_id."""
        return len(self.positions(term, doc_id))

    def cf(self, term: str) -> int:
        """Return the number of times term occurs in the whole collection."""
        return sum(len(p) for p in self._pos.get(term, []))

    def terms(self) -> list[str]:
        """Return the terms of the index in sorted order."""
        return sorted(self._ids)

    def check_invariant(self) -> None:
        """Raise AssertionError unless all ids and all position lists are strictly increasing."""
        for term, ids in self._ids.items():
            pos = self._pos[term]
            assert len(ids) == len(pos)
            for i in range(1, len(ids)):
                assert ids[i - 1] < ids[i]
            for p in pos:
                assert p
                for i in range(1, len(p)):
                    assert p[i - 1] < p[i]


def build_positional_index(docs: dict[int, Sequence[str]]) -> PositionalIndex:
    """Build the positional index of a tokenized collection, reading the ids in increasing order."""
    index = PositionalIndex()
    for d in sorted(docs):
        index.add_document(d, docs[d])
    return index
test_positional_index.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/positional-index/. The authors are listed in prov/F109TQ.jsonl.

import random

import irtoy
from positional_index import PositionalIndex, build_positional_index


def toy_index() -> PositionalIndex:
    return build_positional_index({d: irtoy.tokenize(t) for d, t in irtoy.DOCS.items()})


def scan_positions(tokens: list[str], term: str) -> list[int]:
    return [i for i, t in enumerate(tokens) if t == term]


def test_example() -> None:
    ix = toy_index()
    assert ix.entries("sorted") == [(1, [7]), (2, [4, 8]), (4, [5]), (8, [1])]
    assert ix.entries("list") == [(3, [9]), (4, [2, 6])]
    assert ix.entries("posting") == [(3, [8]), (4, [1]), (5, [8])]
    assert ix.positions("a", 4) == [0, 4]
    assert ix.positions("a", 2) == []
    assert ix.positions("quantum", 1) == []
    assert ix.postings("array") == [1, 2, 8]
    assert ix.tf("sorted", 2) == 2


def test_irtoy_statistics() -> None:
    ix = toy_index()
    ix.check_invariant()
    terms = ix.terms()
    assert len(terms) == 50
    assert sum(ix.df(t) for t in terms) == 74
    assert sum(ix.cf(t) for t in terms) == 79
    for t in terms:
        assert ix.df(t) == irtoy.df(t)
        assert ix.cf(t) == irtoy.cf(t)
        for d in irtoy.DOCS:
            tokens = irtoy.tokenize(irtoy.DOCS[d])
            assert ix.positions(t, d) == scan_positions(tokens, t)
            assert ix.tf(t, d) == irtoy.tf(t, d)


def test_order_check() -> None:
    ix = PositionalIndex()
    ix.add_document(3, ["a", "b"])
    for bad in (3, 1):
        try:
            ix.add_document(bad, ["a"])
        except ValueError:
            pass
        else:
            raise AssertionError("an id out of order was accepted")
    ix.add_document(7, [])
    ix.add_document(9, ["b", "b", "b"])
    assert ix.entries("b") == [(3, [1]), (9, [0, 1, 2])]
    assert ix.entries("zzz") == []


def test_random_collections() -> None:
    rng = random.Random(1709)
    for _ in range(200):
        vocab = [f"w{i}" for i in range(rng.randint(1, 12))]
        ids = sorted(rng.sample(range(1000), rng.randint(0, 30)))
        docs = {d: [rng.choice(vocab) for _ in range(rng.randint(0, 40))] for d in ids}
        ix = build_positional_index(docs)
        ix.check_invariant()
        total = 0
        for t in vocab:
            expect = [(d, scan_positions(docs[d], t)) for d in ids if t in docs[d]]
            assert ix.entries(t) == expect
            assert ix.postings(t) == [d for d, _ in expect]
            total += ix.cf(t)
            for d in ids:
                assert ix.positions(t, d) == scan_positions(docs[d], t)
        assert total == sum(len(v) for v in docs.values())

History

Manning, Raghavan and Schuetze present biword indexes and positional indexes as the two ways to support phrase queries, and give the positional intersection of two lists. Witten, Moffat and Bell treat word-level indexes with gap codes in Managing Gigabytes, and Zobel and Moffat describe the layout of document ids, frequencies and positions in their survey of inverted files in 2006.

References

  1. Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 2, Section 2.4.1 (biword indexes) and Section 2.4.2 (positional indexes, their postings of the form document and positions, and the positional intersection of two lists)
  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 (an inverted index of term positions with the methods first, last, next and prev, and phrase search with it)
  3. Justin Zobel and Alistair Moffat, Inverted files for text search engines, ACM Computing Surveys 38(2), Article 6, 2006, the inverted list with in-document frequencies and word positions, and the compression of position gaps
  4. Ian H. Witten, Alistair Moffat and Timothy C. Bell, Managing Gigabytes, second edition, Morgan Kaufmann, 1999, Chapter 3 (inverted file indexing, the granularity of an index and word-level indexes)

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.add_document
  • a full proof of time.build
  • a full proof of time.positions
  • 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/F109TQ/text.yaml