Algorithmadvanced
MaxScore
Also called Turtle-Flood MaxScore.
Splits query terms into essential and nonessential by their score upper bounds, and skips documents that only nonessential terms could lift into the top k.
- Solves
- Ranked retrieval
- Time
- O(T (m log T + log k)) worst
- Space
- O(m + k) extra
- Where
- T = the total length of the m posting lists; k = the number of results; m = the number of query terms
- Model
- Word RAM
- Properties
- deterministiconlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Howard Turtle, James Flood, 1995
MaxScore is a dynamic pruning method for ranked retrieval on a docid-ordered index. It sorts the query terms by their upper bounds , the largest weight in each posting list, from small to large. When the heap of the best is full with threshold , the longest prefix of terms whose bounds sum to at most is nonessential: a document that contains only these terms cannot enter the top . So the candidates come only from the essential lists, read as in document-at-a-time evaluation. The nonessential lists are only probed, with forward searches, for the candidates, and the probes stop as soon as the partial score plus the bounds of the terms not yet probed is at most . As grows, more terms become nonessential. With exact arithmetic MaxScore is safe: it returns exactly the top of exhaustive scoring. WAND uses the same bounds but chooses a pivot again at each step.
In plain words
Each query word has a best possible contribution. Put the words in order from the weakest to the strongest. Once you have a list of top results, add up the weak words from the bottom. If even all of them together cannot beat the worst current result, then a document that has only weak words can never make the list. So look for candidates only in the lists of the strong words. For each candidate, add the strong words first, and then check the weak words one by one. Stop checking as soon as the candidate cannot win even with the best values of the words that remain.
The problem
The input is a query of distinct terms, the posting list of each term in increasing docid order with weights , and . The score of a document is the sum of the weights of the query terms that it contains, and a document matches if it contains at least one. The output is the matching documents of highest score, by score descending and then docid ascending. Each list supports next and , a forward search to the first posting with docid at least , for example with skip pointers.
The algorithm
The heap is the one of DAAT: it holds the best pairs so far and replaces its least entry only on a strictly greater score. While it has fewer than entries, there is no threshold and every term is essential.
MAXSCORE(q, k)- 1
sort the cursors so that U_1 ≤ U_2 ≤ … ≤ U_m - 2
P_0 ← 0; for i ← 1 to m do P_i ← P_(i-1) + U_i ▷ prefix sums of the bounds - 3
H ← an empty heap of size k; θ is the least score in H when |H| = k; e ← 0 - 4
loop ▷ terms 1..e are nonessential - 5
while |H| = k and e < m and P_(e+1) ≤ θ do e ← e + 1 - 6
d ← the least docid of the cursors e+1, …, m - 7
if d = ∞ then return the entries of H, by score descending and then docid ascending - 8
s ← the sum of the weights of the essential cursors at d; move each of them by next - 9
for i ← e down to 1 do - 10
if s + P_i ≤ θ then go to L4 without a score ▷ d cannot enter the top k - 11
c_i.next_geq(d); if c_i.docid = d then s ← s + its weight - 12
offer (s, d) to H
The test in line L10 uses , the bounds of the nonessential terms that are not yet probed. Line L10 can only be true when , so the heap is full and exists. The split never goes down, since only grows.
Example
Take the toy collection with BM25 weights (, , the Lucene IDF with the natural log), q1 "sorted array search" and . Sorted by bound: sorted (), array (), search (), with prefix sums , and . The lists are sorted: d1, d2, d4, d8; array: d1, d2, d8; search: d1, d7.
| candidate | before | nonessential | action |
|---|---|---|---|
| d1 | none | none | full score 3.0283, into the heap |
| d2 | none | none | full score 1.8893, into the heap; now |
| d7 | 1.8893 | sorted | essential part 1.2743; , so probe sorted: no d7; full score 1.2743, rejected |
| d8 | 1.8893 | sorted | essential part 0.9396 (array); , so stop |
| none | 1.8893 | sorted | the essential lists are at the end; return |
After d2, makes sorted nonessential, and keeps array and search essential. The document d4, which contains only sorted, is never a candidate. MaxScore fully scored 3 of the 5 matching documents and returns d1 3.0283 and d2 1.8893, as DAAT does. For d8, the bound test meets with equality, and the tie rule makes this right: a score of 1.8893 at d8 would lose to d2, which has the smaller docid.
Correctness
The proof uses three conditions. (1) Each bound is at least every weight of list , and the prefix sums and scores are computed exactly. (2) The heap replaces its least entry only on a strictly greater score, and the candidates come in increasing docid order, so a tie keeps the smaller docid. (3) Each document left out has a score of at most . The essential cursors move as in DAAT, so each candidate is the next document of the essential lists, and every essential list that contains it has its cursor on it. The nonessential cursors have never moved past a document after the last candidate, so each probe finds the candidate if and only if the list contains it. A document that is never a candidate is in no essential list at the time the essential cursors pass it, so its score is at most . A candidate stopped by line L10 has a score at most . In both cases the full heap holds documents with smaller docids and scores at least . The full proof is in the proof file.
Proof: MaxScore returns the exact top k under the tie rulefull
The rank order is score descending, then docid ascending, and is the first pairs of a set in this order. Let be the set of matching documents and the score of . A pass is one run of lines L5 to L12, or L5 to L10 when line L10 stops it. The candidate of a pass is the of line L6. The cursors are numbered in the order of line L1, so is the bound sum of cursors .
The three conditions.
(C1) Each weight is at least 0, is at least every weight of list , and the sums are computed exactly, or in an arithmetic in which a sum of numbers each at most its partner is at most the sum of the partners.
(C2) The heap replaces its least entry only on a strictly greater score, and documents are offered in increasing docid order.
(C3) Each document left out has a score of at most the current threshold .
(C1) is an assumption; (C2) and (C3) are proved below.
Lemma 1 (the split). The value never decreases. After line L5 of each pass, implies that the heap is full and .
Proof. Line L5 only increases , and only when the heap is full and . Once the heap is full it stays full, and never decreases, so stays true.
Lemma 2 (the cursors). Let be the candidate of the previous pass, or before the first pass. At the start of each pass:
(M1) each cursor is at the first posting of its list with docid greater than ;
(M2) each cursor is at a posting with docid at most the first docid of its list that is greater than .
Proof. At the start every cursor is at the first posting of its list, so (M1) and (M2) hold. Assume them at the start of a pass with candidate . Line L5 moves some cursors from the essential to the nonessential group, and (M1) for a cursor implies (M2) for it, so both still hold. By (M1), each essential cursor is at a docid greater than , and is the least of them, so . Line L8 moves each essential cursor at to the next posting, which is the first posting greater than . The other essential cursors are already at docids greater than , and since they were at the first posting greater than and , they are at the first posting greater than . So (M1) holds with in place of . A nonessential cursor is either left alone, and then by (M2) it is at most the first docid greater than , which is at most the first docid greater than ; or line L11 moves it to the first docid at least , which is at most the first docid greater than . In both cases (M2) holds with .
Lemma 3 (candidates and their scores). The candidates are strictly increasing. Each candidate that reaches line L12 is offered with .
Proof. The order is the step in the proof of Lemma 2. For the score: by (M1), an essential list contains if and only if its cursor is at , so line L8 adds the weights of exactly the essential terms that contains. For a nonessential cursor , (M2) says that it has not passed any docid greater than , and , so line L11 finds if and only if list contains . If line L10 never stops, every nonessential term is probed, and .
Lemma 4 (documents left out). If a matching document is never offered, then at some time the heap holds documents, each with a score at least and a docid less than .
Proof. There are two cases.
Case A: is a candidate, and line L10 stops it at index . At that time is the sum of the weights in of the essential terms and of the nonessential terms , by Lemma 3. The terms contribute at most by (C1). So . Since and , the heap is full by Lemma 1.
Case B: is never a candidate. Take the first pass whose candidate is greater than , or, if there is none, the pass that ends in line L7 with . Let be the candidate before it; then , since the candidates are increasing, none of them is , and is the first one above . Suppose an essential list of this pass contains . By (M1) its cursor is at the first posting greater than , which is at most , so , which is false. So is only in the lists of this pass, and by (C1) and Lemma 1. Since matches, , so the heap is full.
In both cases the heap is full and each entry has a score at least . Each entry was offered in an earlier pass, so its docid is an earlier candidate, which is less than in case A by Lemma 3 and at most in case B.
Theorem. Under (C1), MAXSCORE returns in the order .
Proof. Let be the set of offered documents with their scores. By Lemma 3 they are offered in increasing docid order with exact scores, so by Lemma 1 of the DAAT proof, the heap rule, the final heap is . By Lemma 4 each ranks after members of , so . Line L7 returns it in the order .
Termination. In each pass the essential cursor at moves one posting in line L8, so there are at most passes. Line L5 and the loop of line L9 do at most steps each.
Remark (ties). Both line L5 and line L10 use . A document left out with score exactly ranks after the heap entries, because they have smaller docids. This needs the increasing order of the candidates and the strict replacement in the heap.
Remark (floating point). Line L10 compares , a sum in one order, with , a score summed in another order. With floating-point weights the bound can come out a little below the true score, and a document of the top can be dropped. With integer or fraction weights, as in the tests, this cannot happen.
Complexity
The model is the word RAM with the index in memory. Let be the total length of the query lists.
- Worst case. Each pass through the loop moves at least one essential cursor by one posting, so there are at most passes. Each pass finds the least essential docid in , does at most forward searches of each with binary search, and one heap operation of . This gives , which is no better than DAAT in the worst case.
- Documents scored. At most the number of matching documents; on the toy query 3 of 5.
- Space. besides the index.
- Measured speed. The speedups of MaxScore over DAAT are measurements, not bounds. The survey of Tonellotto and others (2018) reviews such measurements against WAND and block-max WAND; which method is fastest depends on the query length, and the collection.
Properties
- Safe under the three conditions, with exact arithmetic or bounds that are rounded up.
- No re-sorting. The terms are sorted once by bound, in line L1. WAND sorts the cursors by docid at each step.
- No random access. All cursors move forward only; the probes are forward searches, not lookups out of order, unlike the threshold algorithm, which uses random access.
- Online. Each scored document is final, and only grows.
- Needs nonnegative weights, so that the prefix sums bound the scores.
Variants and improvements
- Term-at-a-time form. The original max_score of Turtle and Flood also has a term-at-a-time form, which stops creating accumulators when the bound of the remaining terms falls below the -th accumulator. It is described on the term-at-a-time evaluation page.
- Block maxes. The bounds of the nonessential terms in line L10 can be replaced by the block max of the block that holds , as in block-max WAND, which stops more probes early.
- Conjunctive queries. When every term must occur, all lists can be probed in order of length, and the bound test still applies.
- Initial threshold. A safe lower bound on the final makes terms nonessential from the start.
When to use it
Use MaxScore for disjunctive queries with small on a docid-ordered index, in particular for longer queries, where the sort of WAND at each step costs more and many low-bound terms become nonessential early. With few terms of similar bound, the split helps little, and WAND or block-max WAND may skip more.
Pitfalls
- Ascending order of bounds. The nonessential terms must be the ones with the smallest bounds. A prefix in another order gives a weaker split, and a split that is not a prefix of some order with is unsafe.
- Equal to the threshold. Line L5 may move a term with , and line L10 may stop with , because a tie is lost by the later docid. This is right only because the candidates come in increasing docid order and the heap replaces only on a strictly greater score.
- Probing past the candidate. Line L11 must move to the first docid at least . Moving to the next posting after , or reusing a cursor that has already moved past , loses weights.
- Float sums. If the prefix sums are rounded down below a computed score, a document can be dropped. Round the bounds up, or use exact weights.
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
maxscore.py 180 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maxscore/. The authors are listed in prov/ZNWK20.jsonl.
"""MaxScore top-k evaluation of a ranked query, document at a time.
An index maps each term to its posting list: 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 terms are sorted by their upper bounds U, the largest weight in each
list, in increasing order, with prefix sums P. The nonessential terms are
the longest prefix whose bound sum P is at most the threshold. A document
that contains only nonessential terms cannot enter the top k, so the
candidates come only from the essential lists. The nonessential lists are
probed with next_geq, and the probes stop early when the partial score
plus the bounds of the unprobed terms is at most the threshold.
The method is safe when the score arithmetic is exact.
"""
import heapq
import math
from bisect import bisect_left
END = math.inf # the docid of a cursor that is past the end of its list
class Stats:
"""Work counters: documents fully scored and posting weights read."""
def __init__(self):
self.scored = 0
self.postings = 0
class Cursor:
"""A forward-only cursor on one posting list, with its upper bound."""
def __init__(self, postings, stats):
self.ids = [d for d, _ in postings]
self.ws = [w for _, w in postings]
self.ub = max(self.ws, default=0)
self.i = 0
self.stats = stats
def docid(self):
return self.ids[self.i] if self.i < len(self.ids) else END
def weight(self):
self.stats.postings += 1
return self.ws[self.i]
def next(self):
self.i += 1
def next_geq(self, d):
"""Move to the first posting with docid >= d."""
self.i = bisect_left(self.ids, d, self.i)
class TopK:
"""The best k (docid, score) pairs seen so far.
The heap holds (score, -docid), so its minimum is the entry that the
tie rule ranks last. A new document replaces it only on a strictly
greater score.
"""
def __init__(self, k):
self.k = k
self.heap = []
def threshold(self):
"""The lowest score in a full heap, or None while it is not full."""
return self.heap[0][0] if len(self.heap) == self.k else None
def offer(self, d, s):
if len(self.heap) < self.k:
heapq.heappush(self.heap, (s, -d))
elif s > self.heap[0][0]:
heapq.heapreplace(self.heap, (s, -d))
def result(self):
return sorted(((-nd, s) for s, nd in self.heap), key=lambda p: (-p[1], p[0]))
def maxscore(index, query, k):
"""Return (the top k as a list of (docid, score), Stats).
query is a list of distinct terms. Terms missing from the index have an
empty posting list.
"""
stats = Stats()
if k <= 0:
return [], stats
cursors = [Cursor(index.get(t, []), stats) for t in query]
cursors.sort(key=lambda c: c.ub) # @line L1
m = len(cursors)
prefix = [0] * (m + 1) # @line L2
for i, c in enumerate(cursors):
prefix[i + 1] = prefix[i] + c.ub
top = TopK(k) # @line L3
e = 0 # cursors[0:e] are nonessential
while True: # @line L4
theta = top.threshold()
while theta is not None and e < m and prefix[e + 1] <= theta: # @line L5
e += 1
d = min((c.docid() for c in cursors[e:]), default=END) # @line L6
if d == END: # @line L7
return top.result(), stats
s = 0 # @line L8
for c in cursors[e:]:
if c.docid() == d:
s = s + c.weight()
c.next()
for i in range(e - 1, -1, -1): # @line L9
if s + prefix[i + 1] <= theta: # @line L10
break
c = cursors[i]
c.next_geq(d) # @line L11
if c.docid() == d:
s = s + c.weight()
else:
stats.scored += 1
top.offer(d, s) # @line L12
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
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 daat_scored(index, query):
"""The number of documents that plain DAAT scores: the matching ones."""
union = set()
for t in query:
union.update(d for d, _ in index.get(t, []))
return len(union)
test_maxscore.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maxscore/. The authors are listed in prov/ZNWK20.jsonl.
import random
from fractions import Fraction
import irtoy
from maxscore import bm25_index, daat_scored, exhaustive_top_k, maxscore
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 close(a, b):
"""Same docids in the same order, and scores equal within 1e-9."""
return [d for d, _ in a] == [d for d, _ in b] and all(abs(x - y) < 1e-9 for (_, x), (_, y) in zip(a, b))
def test_toy_check_values():
index = toy_index()
q1 = irtoy.tokenize(irtoy.QUERIES["q1"])
got, stats = maxscore(index, q1, 5)
assert [d for d, _ in got] == [1, 2, 8, 7, 4]
want = [3.0283, 1.8893, 1.6292, 1.2743, 0.6896]
assert all(abs(s - w) < 5e-5 for (_, s), w in zip(got, want))
assert stats.scored == 5
got, _ = maxscore(index, irtoy.tokenize(irtoy.QUERIES["q2"]), 3)
assert [d for d, _ in got] == [4, 3, 5]
assert maxscore(index, irtoy.tokenize(irtoy.QUERIES["q4"]), 5)[0] == []
def test_toy_nonessential():
# q1 with k = 2: after d1 and d2 the threshold is 1.8893. The bounds in
# increasing order are 0.9497 (sorted), 0.98 (array) and 1.3291
# (search), with prefix sums 0.9497 and 1.9297, so "sorted" becomes
# nonessential. d4 contains only "sorted" and is never a candidate.
# d7 is scored fully. For d8 the partial score 0.9396 of "array" plus
# the bound 0.9497 of "sorted" equals the threshold, so the probe of
# "sorted" is skipped and d8 is not scored fully.
index = toy_index()
got, stats = maxscore(index, irtoy.tokenize(irtoy.QUERIES["q1"]), 2)
assert [d for d, _ in got] == [1, 2]
assert stats.scored == 3
def test_toy_against_exhaustive():
index = toy_index()
for text in irtoy.QUERIES.values():
q = irtoy.tokenize(text)
for k in range(0, 10):
got, stats = maxscore(index, q, k)
assert close(got, exhaustive_top_k(index, q, k, irtoy.DOCS))
assert stats.scored <= daat_scored(index, q)
def test_edges():
index = {"a": [(1, 3), (4, 1)], "b": [(4, 2)]}
assert maxscore(index, [], 3)[0] == []
assert maxscore(index, ["a"], 0)[0] == []
assert maxscore(index, ["zz"], 3)[0] == []
assert maxscore(index, ["a", "b"], 1)[0] == [(1, 3)]
assert maxscore(index, ["a", "b"], 5)[0] == [(1, 3), (4, 3)]
assert maxscore({"a": [(1, 3), (2, 3), (3, 3)]}, ["a"], 2)[0] == [(1, 3), (2, 3)]
def test_random_against_exhaustive():
rng = random.Random(20251119)
total_ms = total_daat = 0
for trial in range(300):
n = rng.randint(1, 200)
index = random_index(rng, n, 8, exact=trial % 2 == 0)
q = rng.sample(sorted(index), rng.randint(1, 5))
if rng.random() < 0.2:
q.append("missing")
k = rng.randint(1, 12)
got, stats = maxscore(index, q, k)
assert got == exhaustive_top_k(index, q, k, range(1, n + 1))
assert stats.scored <= daat_scored(index, q)
total_ms += stats.scored
total_daat += daat_scored(index, q)
assert total_ms < total_daat
History
Turtle and Flood (1995) gave the max_score optimization for both term-at-a-time and document-at-a-time evaluation. Strohman, Turtle and Croft (2005) used the document-at-a-time form for complex queries. The split into essential and nonessential lists, with the prefix sums of the sorted bounds, is the form of MaxScore that later studies of dynamic pruning use, for example the survey of Tonellotto, Macdonald and Ounis (2018).
References
- Howard Turtle and James Flood, Query evaluation, strategies and optimizations, Information Processing and Management 31(6), 1995, 831-850, the max_score optimization for term-at-a-time and document-at-a-time evaluation
- Trevor Strohman, Howard Turtle and W. Bruce Croft, Optimization strategies for complex queries, SIGIR 2005, the document-at-a-time form of max_score and its use for complex queries
- 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 chapter on dynamic pruning, with the essential and nonessential lists of MaxScore and the safety of the method
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 | W2 basic |
|
Tag ZNWK20 Edit this page History Report an error Markdown