Data structurecore
Tiered index
Also called champion lists.
Splits each posting list into tiers by score, and reads lower tiers only when the higher tiers give fewer than k results.
- Time
- O(n log r) buildO(T m + r T log k) expected query
- Space
- Θ(n) total
- Where
- T = the total length of the query lists; k = the number of results; m = the number of query terms; n = the number of postings in the index; r = the number of weight thresholds
- Model
- Word RAM
- Properties
- not concurrentnot externalnot persistent
- Evidence
- Proof sketchCode in 1 languages
A tiered index is an inverted index in which each posting list is cut into a few tiers by the weight of the term in the document. With thresholds , tier 1 holds the postings with weight at least , tier the postings with weight from up to but not including , and tier the rest. A query reads tier 1 of all its terms, then tier 2, and so on, and computes the full score of each new document. The approximate rule of Manning, Raghavan and Schuetze stops as soon as at least documents are found. A safe rule stops after tier only when the -th best full score is at least , where is the number of query terms; every unseen document has a score strictly below this bound. The approximate rule is fast and can miss documents; the safe rule returns exactly the top of exhaustive scoring.
In plain words
Put the best postings of each word on a short list, the next best on a second list, and the rest on a third. To answer a query, read the short lists first and compute the real score of every document that you find there. If that gives enough good results, stop. Otherwise read the second lists, and so on. The quick version stops as soon as it has enough results, and it can miss a document that is good in many words but best in none. The careful version also checks that the results it has beat anything that could still be hiding in the lists not yet read.
The abstract type
A tiered index over a docid-ordered index with weights holds, for each term and each tier , the sorted list of docids whose weight of falls in tier . Each posting is in exactly one tier. The index also keeps random access to the weight of in , for example a hash table or the docid-ordered lists. The score of a document for a query of distinct terms is the sum of the weights of the query terms in it. The operations are:
- build from the docid-ordered index;
- tier, the docids of tier of term ;
- query, which returns documents with their full scores, by score descending and then docid ascending, with the safe or the approximate stop rule.
Representation
Each tier of each term is a short docid-ordered posting list, so the usual compression applies. The thresholds are global in this page, the same for all terms; MRS also allows a threshold for each term. The full score of a new document needs the weights of all query terms in it, which come from a second, docid-ordered copy of the lists or from a forward index. The total size is for the tiers plus the size of this second copy.
Operations
TIERED-SEARCH(q, k, stop)- 1
F ← an empty map from docid to full score - 2
for j ← 1 to r + 1 do - 3
for each query term t and each docid x in tier(t, j) do - 4
if x ∉ F then - 5
F[x] ← the full score of x, by random access to the weight of each query term - 6
if stop = approx and |F| ≥ k then break - 7
if stop = safe and j ≤ r and |F| ≥ k and the k-th best score in F ≥ m τ_j then break - 8
return the k best entries of F, by score descending and then docid ascending
After tier , every weight not yet read is less than , so a document that is not in has a score less than . This is the reason line L7 can use "at least". After tier every posting has been read.
Example
Take the toy collection with BM25 weights (, , the Lucene IDF with the natural log) and the thresholds , . Tier 1 holds the strongest postings of the collection, for example list in d4 (1.755) and rank in d7 (1.7825). For q1 "sorted array search", tier 1 has no posting, tier 2 has search in d1 and d7, and tier 3 has sorted in d1, d2, d4, d8 and array in d1, d2, d8.
- . After tier 2, = {d1 3.0283, d7 1.2743}. The best score , so the safe rule stops after reading 2 postings and scoring 2 documents, with d1, which is the true top 1.
- , approximate rule. After tier 2 there are 2 documents, so it stops and returns d1 3.0283 and d7 1.2743. The true second is d2 1.8893, which has no posting in tier 2: d2 is good in sorted and array but best in neither.
- , safe rule. After tier 2 the second best score is , so it reads tier 3 and returns d1 3.0283 and d2 1.8893.
Correctness
Line L5 gives each document of its true score, so both rules return true scores in the order of the tie rule. For the safe rule, suppose that line L7 stops after tier . A matching document that is not in has no posting in tiers for any query term. So each of its query weights is less than , and at least one is present, so , which is at most the -th best score in . Each of these documents ranks before , so the top of is the top of all documents. If no stop happens, holds all matching documents. The approximate rule has only the weaker property that its documents carry their true scores; the toy example above shows that it can miss a document of the true top . The full proof is in the proof file.
Proof: The safe tier rule returns the exact top k, and the approximate rule returns true scoresfull
The rank order is score descending, then docid ascending, and is the first pairs of a set in this order. The query has distinct terms, is the set of matching documents, and is the score of . The weights are at least 0, the thresholds satisfy , and weights, thresholds and scores are exact numbers.
Lemma 1 (tiers). Each posting is in exactly one tier. A posting with weight is in a tier if and only if , for each .
Proof. The build puts in the least tier with , or in tier if there is none. Since the thresholds decrease, holds if and only if that least is at most .
Lemma 2 (the map). After tier has been read, has an entry for if and only if some query term has a posting of in tiers , and then .
Proof. Lines L3 and L4 add an entry for each new docid met in the tiers read so far, and line L5 computes it by random access to every query term, so the entry is the sum of all the query weights of .
Lemma 3 (unseen documents). After tier , every with no entry in has .
Proof. By Lemma 2, no query term has a posting of in tiers , so by Lemma 1 each query weight of is less than . The document has at most such weights and at least one, since it matches, so the sum is less than .
Theorem 1 (safe rule). TIERED-SEARCH returns in the order .
Proof. If the loop reads all tiers, then holds every posting of the query terms, so by Lemma 2 it maps each to , and line L8 returns the top . Otherwise line L7 breaks after a tier , with and the -th best score in at least . Let be the set of documents in with their scores, and take with no entry. By Lemma 3, , so each of the best documents of has a score strictly greater than and ranks before . So no such is in , and , which line L8 returns.
Proposition 2 (approximate rule). TIERED-SEARCH returns documents of , each with its true score, in the order . It reads no more tiers than the safe rule.
Proof. Each entry of is a document of with its true score by Lemma 2, and line L8 sorts by . If line L6 breaks, and entries are returned. If it never breaks, all tiers are read and holds all of , so entries are returned. The approximate rule breaks after the first tier at which , and the safe rule cannot break before that tier, since it also needs .
The approximate rule does not return in general. In the toy example of the page, with , q1 and , it returns d1 and d7, while the true second document is d2.
Remark (strictness). Line L7 may use because Lemma 3 is strict: the weights in later tiers are strictly less than . If the build put the weights equal to into tier , the bound would be , and the test would need , or a tie with a smaller docid could be lost.
Remark (tighter bounds). A smaller bound in place of is also safe if every unseen document is strictly below it. An example is the sum over the query terms of , where is the largest weight of term , provided that the build and the test use the same numbers.
Complexity
The model is the word RAM with the index in memory. Let be the number of postings in the index, the number of thresholds, and the total length of the query lists.
- Build. Each posting finds its tier by a binary search over the thresholds, in total.
- Query. At most tier postings are read, and each new document costs expected lookups, so expected. The test of line L7 selects the best of at most scores after each of at most tiers, . In the good case only the first tiers are read, and the cost depends on their length, not on .
- Space. for the tiers, plus the copy for random access.
Variants
- Champion lists. MRS (Section 7.1.3) keep, for each term, a champion list of a fixed number of documents with the highest weights for that term, and score only the union of the champion lists of the query terms. This is a different structure from a tiered index: it has one cut for each term, by rank in the list and not by a weight threshold, and no lower tiers to fall back on. MRS describe tiered indexes as a generalization of champion lists.
- Thresholds for each term. A cut by rank or by a weight threshold for each term in place of global thresholds. The safe rule then uses the sum of the thresholds of the query terms in place of .
- Document tiers. Risvik, Aasheim and Lidal (2003) split a web index by documents, with the most useful documents in the first tier, and send a query to a lower tier only when the first tier does not give a good enough answer.
- Link to the threshold algorithm. The safe rule is a coarse form of the stop rule of the threshold algorithm: sorted access by tiers, random access for the full score, and a stop when the -th score reaches a bound on all unseen documents. Fagin's algorithm is the older method of this family.
- Static pruning. Dropping the last tier is static index pruning; it saves space but is lossy.
When to use it
Use a tiered index when most queries are answered well by the strongest postings, and a fast approximate answer is acceptable, for example in a first stage of a large web engine. With the safe rule, use it when the strong postings of the query terms are rare and the -th score after the first tiers is often high; else the safe rule falls back to the lower tiers and does more work than a single pass.
Pitfalls
- Calling the approximate rule exact. The rule "stop when documents are found" can miss a document that is good in many terms but has no strong posting. Report it as approximate.
- Bound from the wrong tier. The safe bound after tier uses , the lower edge of tier , not or .
- Partial scores. Line L5 must compute the full score by random access. Adding only the weights seen in the read tiers gives lower bounds, and then the safe rule is wrong.
- Count of terms. The bound needs to count every query term that has a posting list. Counting fewer is unsafe.
- Float thresholds. A weight that is rounded across a threshold goes into the wrong tier, and the bound can then fail. Build the tiers and the bound from the same numbers.
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
tiered_index.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tiered-index/. The authors are listed in prov/J6839A.jsonl.
"""A tiered index and top-k query evaluation over its tiers.
A document-ordered index maps each term to a list of (docid, weight)
pairs in increasing docid order, with weights at least 0. The score of a
document is the sum of the weights of the query terms that it contains.
A document matches when it contains at least one query term. Results rank
by score descending, then by docid ascending.
The tiered index cuts each posting list by global weight thresholds
tau_1 > tau_2 > ... > tau_r > 0. Tier 1 holds the postings with weight at
least tau_1, tier j the postings with tau_j <= w < tau_(j-1), and the last
tier, r + 1, the postings with w < tau_r. Each tier list is in docid order.
search reads the tiers in order. For each document that it meets for the
first time it computes the full score by random access to the
document-ordered lists. It has two stop rules:
"safe" after tier j, stop when the k-th best full score is at least
the sum of tau_j over the query terms. Every unseen document
has a smaller score, so the result is the exact top k.
"approx" after a tier, stop when at least k documents have been seen.
This is the rule in Manning, Raghavan and Schuetze, 7.2.1. It
returns true scores, but can miss documents of the true top k.
"""
import heapq
import math
class Stats:
"""Work counters: documents fully scored, tier postings read, random
accesses made, and tiers read."""
def __init__(self):
self.scored = 0
self.postings = 0
self.lookups = 0
self.tiers = 0
def build(index, taus):
"""Build the tiers. taus is strictly decreasing and positive."""
tiers = [{} for _ in range(len(taus) + 1)]
for t, plist in index.items():
for d, w in plist:
j = 0
while j < len(taus) and w < taus[j]:
j += 1
tiers[j].setdefault(t, []).append(d)
return tiers
def best_k(full, k):
"""The k best (docid, score) pairs, by the tie rule."""
return heapq.nsmallest(k, full.items(), key=lambda p: (-p[1], p[0]))
def search(index, tiers, taus, query, k, stop="safe"):
"""Return (the top k as a list of (docid, score), Stats)."""
stats = Stats()
if k <= 0:
return [], stats
lookup = [dict(index.get(t, [])) for t in query]
full = {} # @line L1
for j, tier in enumerate(tiers): # @line L2
stats.tiers += 1
for t in query: # @line L3
for d in tier.get(t, []):
stats.postings += 1
if d not in full: # @line L4
s = 0
for table in lookup:
stats.lookups += 1
if d in table:
s = s + table[d]
stats.scored += 1
full[d] = s # @line L5
if j == len(taus):
break
if stop == "approx" and len(full) >= k: # @line L6
break
if stop == "safe" and len(full) >= k: # @line L7
bound = taus[j] * len(query)
if best_k(full, k)[-1][1] >= bound:
break
return best_k(full, k), stats # @line L8
def exhaustive_top_k(index, query, k, doc_ids):
"""Score every document of doc_ids, then sort. The reference method."""
if k <= 0:
return []
lookup = [dict(index.get(t, [])) for t in query]
scored = []
for d in doc_ids:
s = 0
hit = False
for table in lookup:
if d in table:
s = s + table[d]
hit = True
if hit:
scored.append((d, s))
scored.sort(key=lambda p: (-p[1], p[0]))
return scored[:k]
def bm25_index(docs, k1=1.2, b=0.75):
"""Build an index of BM25 term weights with the Lucene IDF.
docs maps docid to a list of tokens. The weight of t in d is
IDF(t) * tf (k1 + 1) / (tf + k1 (1 - b + b |d| / avgdl)) with
IDF(t) = ln(1 + (N - df + 0.5) / (df + 0.5)), which is positive.
"""
n = len(docs)
avgdl = sum(len(toks) for toks in docs.values()) / n
counts = {}
for d in sorted(docs):
seen = {}
for tok in docs[d]:
seen[tok] = seen.get(tok, 0) + 1
for t, f in seen.items():
counts.setdefault(t, []).append((d, f))
index = {}
for t, plist in counts.items():
df = len(plist)
idf = math.log(1 + (n - df + 0.5) / (df + 0.5))
index[t] = [
(d, idf * f * (k1 + 1) / (f + k1 * (1 - b + b * len(docs[d]) / avgdl)))
for d, f in plist
]
return index
test_tiered_index.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tiered-index/. The authors are listed in prov/J6839A.jsonl.
import random
from fractions import Fraction
import irtoy
from tiered_index import bm25_index, build, exhaustive_top_k, search
def toy_index():
return bm25_index({d: irtoy.tokenize(t) for d, t in irtoy.DOCS.items()})
def random_index(rng, n, vocab, exact):
"""A random index on docids 1..n with nonnegative weights.
exact selects Fraction weights; else small integers, which give many
ties.
"""
index = {}
for t in range(vocab):
density = rng.random() ** 2
ids = [d for d in range(1, n + 1) if rng.random() < density]
if exact:
index[f"t{t}"] = [(d, Fraction(rng.randint(0, 40), rng.randint(1, 6))) for d in ids]
else:
index[f"t{t}"] = [(d, rng.randint(0, 5)) for d in ids]
return index
def test_toy_tiers():
index = toy_index()
taus = [1.5, 1.0]
tiers = build(index, taus)
assert tiers[0]["list"] == [4] and tiers[0]["rank"] == [7]
assert "search" not in tiers[0] and tiers[1]["search"] == [1, 7]
assert tiers[2]["sorted"] == [1, 2, 4, 8] and tiers[2]["array"] == [1, 2, 8]
q1 = irtoy.tokenize(irtoy.QUERIES["q1"])
# k = 1: after tier 2 the best score 3.0283 is at least 3 * 1.0.
got, stats = search(index, tiers, taus, q1, 1)
assert [d for d, _ in got] == [1] and stats.tiers == 2 and stats.scored == 2
# k = 2: the approximate rule stops after tier 2 with d1 and d7, and
# misses d2. The safe rule reads tier 3 and finds d2.
got, _ = search(index, tiers, taus, q1, 2, "approx")
assert [d for d, _ in got] == [1, 7]
got, stats = search(index, tiers, taus, q1, 2)
assert [d for d, _ in got] == [1, 2] and stats.tiers == 3
def test_toy_safe_against_exhaustive():
index = toy_index()
for taus in ([1.5, 1.0], [2.0], [1.0, 0.9, 0.7], [5.0]):
tiers = build(index, taus)
for text in irtoy.QUERIES.values():
q = irtoy.tokenize(text)
for k in range(0, 10):
got, _ = search(index, tiers, taus, q, k)
assert got == exhaustive_top_k(index, q, k, irtoy.DOCS)
def test_edges():
index = {"a": [(1, 3), (4, 1)], "b": [(4, 2)]}
taus = [2]
tiers = build(index, taus)
assert tiers == [{"a": [1], "b": [4]}, {"a": [4]}]
for stop in ("safe", "approx"):
assert search(index, tiers, taus, [], 3, stop)[0] == []
assert search(index, tiers, taus, ["a"], 0, stop)[0] == []
assert search(index, tiers, taus, ["zz"], 3, stop)[0] == []
assert search(index, tiers, taus, ["a", "b"], 5, stop)[0] == [(1, 3), (4, 3)]
assert search(index, tiers, taus, ["a", "b"], 1)[0] == [(1, 3)]
def test_random():
rng = random.Random(20251121)
missed = 0
for trial in range(300):
n = rng.randint(1, 200)
index = random_index(rng, n, 8, exact=trial % 2 == 0)
weights = sorted({w for p in index.values() for _, w in p if w > 0}, reverse=True)
taus = sorted(rng.sample(weights, min(len(weights), rng.randint(1, 4))), reverse=True)
tiers = build(index, taus)
q = rng.sample(sorted(index), rng.randint(1, 5))
if rng.random() < 0.2:
q.append("missing")
k = rng.randint(1, 12)
union = {d for t in q for d, _ in index.get(t, [])}
want = exhaustive_top_k(index, q, k, range(1, n + 1))
true = dict(exhaustive_top_k(index, q, n, range(1, n + 1)))
# The safe rule: the exact top k.
got, safe = search(index, tiers, taus, q, k)
assert got == want
assert safe.scored <= len(union)
# The approximate rule: min(k, matches) documents with their true
# scores, in tie-rule order, after no more work than the safe rule.
got, approx = search(index, tiers, taus, q, k, "approx")
assert len(got) == min(k, len(union))
assert all(d in union and s == true[d] for d, s in got)
assert got == sorted(got, key=lambda p: (-p[1], p[0]))
assert approx.scored <= safe.scored
missed += got != want
assert missed > 0
History
Manning, Raghavan and Schuetze (2008) describe champion lists and tiered indexes as heuristics for fast inexact top retrieval. Risvik, Aasheim and Lidal (2003) described a multi-tier architecture for web search engines, with tiers of documents. Fagin, Lotem and Naor's threshold algorithm gives the stop rule that the safe version of this page follows.
References
- Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 7, Section 7.1.3 (champion lists) and Section 7.2.1 (tiered indexes, as a generalization of champion lists, with the rule that falls back to the next tier when fewer than k documents are found)
- Knut Magne Risvik, Yngve Aasheim and Mathias Lidal, Multi-tier architecture for web search engines, LA-WEB 2003, the split of a web index into tiers of documents, with a query sent to the lower tiers only when the higher tiers do not give a good enough answer
- Nicola Tonellotto, Craig Macdonald and Iadh Ounis, Efficient query processing for scalable web search, Foundations and Trends in Information Retrieval 12(4-5), 2018, 319-500, the parts on tiering and on early termination of query processing
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 J6839A Edit this page History Report an error Markdown