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
- Model
- Word RAM
- Properties
- not concurrentnot externalnot persistent
- Evidence
- Proof sketchCode in 1 languages
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: add a document with an id greater than all ids before.
- POSTINGS: the increasing ids of the documents that hold term .
- POSITIONS: the increasing positions with in document , or the empty list.
- ENTRIES: the positional posting list of , the pairs in increasing order of , which is the input of positional intersection.
- The statistics , and , the sum of over all .
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 . 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
ADD-DOCUMENT(I, d, t_0, ..., t_{L-1}) ▷ d greater than every id in I- 1
if I has a document and not (the last id < d) then error "out of order" - 2
for i ← 0 to L - 1 do - 3
P ← the positional list of t_i, made empty if t_i is new ▷ hash table - 4
if P is empty or the last id of P ≠ d then append (d, ()) to P - 5
append i to the positions of the last entry of P POSITIONS(I, w, d)- 6
if w has no list then return () - 7
p ← the least index with p = |P.ids| or P.ids[p] ≥ d ▷ binary search - 8
if p < |P.ids| and P.ids[p] = d then return P.pos[p] - 9
return ()
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 | , , , |
| posting | 3 | , , |
| list | 2 | , |
Document 2 is "merge sort merges two sorted runs into one sorted array", so "sorted" stands at positions 4 and 8, and .
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, is a position of "list", and in document 4, 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 added in this order, and document is the token sequence . For a term , let in increasing order, and for a document let in increasing order. The index stores, for each term that it has seen, an array and an array of the same length.
Invariant (P). After the first documents are added, for every term : is restricted to , and for each index . 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 be greater than every id added before, and let (P) hold for the first documents. We show by induction on that after the token is handled, for every term :
- if occurs in , then is restricted to , followed by , and the last entry of is ;
- else and are as before the call.
Before the first token, the second case holds for every term. Let . Line L3 finds or creates the lists of . If did not occur in , then the last id of , if there is one, is an earlier document, so it is less than and not equal to it. Line L4 appends with an empty position list, and line L5 appends , which gives the list . If did occur, the last id is , line L4 does nothing, and line L5 appends to the last position list. Since is greater than every position of that list, the list stays increasing and equals . Other terms do not change.
After the last token, every term of has appended once, at the end, with the full position list . Since is greater than every earlier id, stays strictly increasing and is restricted to . Terms that do not occur in do not change. So (P) holds for documents.
Lemma 2. POSITIONS returns , which is the empty list when does not occur in .
Proof. If 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 with or , by binary search on the strictly increasing array . If , then , and by (P) line L8 returns . Else is not in , because every id before index is less than and every id from on is greater, so does not occur in and line L9 returns the empty list.
Theorem. After the documents are added, POSTINGS, POSITIONS, , and .
Proof. (P) holds with no documents, because no term has an entry. By Lemma 1 and induction on , it holds after all documents. The claims on POSTINGS and on the counts follow from (P), and the claim on POSITIONS is Lemma 2.
Space. Each token 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 tokens, the index holds positions and at most ids, plus one dictionary entry for each distinct term, at most of them. So the space is words for a collection with .
Time. Line L3 is one lookup in a hash table, expected, and lines L4 and L5 are amortized appends. So ADD-DOCUMENT costs expected, and the whole build costs expected. POSITIONS makes comparisons in line L7 and copies positions.
Complexity
- Space. One position for each token and one id for each pair of a term and a document that holds it, so words for tokens. A plain index stores only the ids, which can be much fewer than when words repeat in a document.
- Build. ADD-DOCUMENT makes one hash lookup and amortized appends for each token, so expected time for a document of tokens and for the collection.
- Lookup. POSITIONS makes comparisons on the ids of a term with documents, then returns its 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.
# 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
- 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)
- 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)
- 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
- 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.
| 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 F109TQ Edit this page History Report an error Markdown