Algorithm Search⌘K

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.

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
Properties
deterministiconlineiterative
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 UiU_i, the largest weight in each posting list, from small to large. When the heap of the best kk is full with threshold θ\theta, the longest prefix of terms whose bounds sum to at most θ\theta is nonessential: a document that contains only these terms cannot enter the top kk. 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 θ\theta. As θ\theta grows, more terms become nonessential. With exact arithmetic MaxScore is safe: it returns exactly the top kk 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 mm distinct terms, the posting list of each term in increasing docid order with weights w≥0w \ge 0, and k≥1k \ge 1. 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 kk matching documents of highest score, by score descending and then docid ascending. Each list supports next and next_geq(d)\mathit{next\_geq}(d), a forward search to the first posting with docid at least dd, for example with skip pointers.

The algorithm

The heap is the one of DAAT: it holds the best kk pairs so far and replaces its least entry only on a strictly greater score. While it has fewer than kk entries, there is no threshold and every term is essential.

  1. MAXSCORE(q, k)
  2. 1sort the cursors so that U_1 ≤ U_2 ≤ … ≤ U_m
  3. 2P_0 ← 0; for i ← 1 to m do P_i ← P_(i-1) + U_i ▷ prefix sums of the bounds
  4. 3H ← an empty heap of size k; θ is the least score in H when |H| = k; e ← 0
  5. 4loop ▷ terms 1..e are nonessential
  6. 5while |H| = k and e < m and P_(e+1) ≤ θ do e ← e + 1
  7. 6d ← the least docid of the cursors e+1, …, m
  8. 7if d = ∞ then return the entries of H, by score descending and then docid ascending
  9. 8s ← the sum of the weights of the essential cursors at d; move each of them by next
  10. 9for i ← e down to 1 do
  11. 10if s + P_i ≤ θ then go to L4 without a score ▷ d cannot enter the top k
  12. 11c_i.next_geq(d); if c_i.docid = d then s ← s + its weight
  13. 12offer (s, d) to H

The test in line L10 uses Pi=U1+⋯+UiP_i = U_1 + \cdots + U_i, the bounds of the nonessential terms that are not yet probed. Line L10 can only be true when e≥1e \ge 1, so the heap is full and θ\theta exists. The split ee never goes down, since θ\theta only grows.

Example

Take the toy collection with BM25 weights (k1=1.2k_1 = 1.2, b=0.75b = 0.75, the Lucene IDF with the natural log), q1 "sorted array search" and k=2k = 2. Sorted by bound: sorted (U=0.9497U = 0.9497), array (0.980.98), search (1.32911.3291), with prefix sums 0.94970.9497, 1.92971.9297 and 3.25883.2588. The lists are sorted: d1, d2, d4, d8; array: d1, d2, d8; search: d1, d7.

candidate θ\theta before nonessential action
d1 none none full score 3.0283, into the heap
d2 none none full score 1.8893, into the heap; now θ=1.8893\theta = 1.8893
d7 1.8893 sorted essential part 1.2743; 1.2743+0.9497>θ1.2743 + 0.9497 > \theta, so probe sorted: no d7; full score 1.2743, rejected
d8 1.8893 sorted essential part 0.9396 (array); 0.9396+0.9497=1.8893≤θ0.9396 + 0.9497 = 1.8893 \le \theta, so stop
none 1.8893 sorted the essential lists are at the end; return

After d2, P1=0.9497≤1.8893P_1 = 0.9497 \le 1.8893 makes sorted nonessential, and P2=1.9297>1.8893P_2 = 1.9297 > 1.8893 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 θ\theta 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 UiU_i is at least every weight of list ii, 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 θ\theta. 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 Pe≤θP_e \le \theta. A candidate stopped by line L10 has a score at most s+Pi≤θs + P_i \le \theta. In both cases the full heap holds kk documents with smaller docids and scores at least θ\theta. The full proof is in the proof file.

Proof: MaxScore returns the exact top k under the tie rulefull

The rank order ≺\prec is score descending, then docid ascending, and topk(S)\mathrm{top}_k(S) is the first min⁡(k,∣S∣)\min(k, |S|) pairs of a set SS in this order. Let MM be the set of matching documents and s(x)s(x) the score of xx. 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 dd of line L6. The cursors are numbered in the order of line L1, so PiP_i is the bound sum of cursors 1,…,i1, \ldots, i.

The three conditions.

(C1) Each weight is at least 0, UiU_i is at least every weight of list ii, 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 θ\theta.

(C1) is an assumption; (C2) and (C3) are proved below.

Lemma 1 (the split). The value ee never decreases. After line L5 of each pass, e≥1e \ge 1 implies that the heap is full and Pe≤θP_e \le \theta.

Proof. Line L5 only increases ee, and only when the heap is full and Pe+1≤θP_{e+1} \le \theta. Once the heap is full it stays full, and θ\theta never decreases, so Pe≤θP_e \le \theta stays true. □\square

Lemma 2 (the cursors). Let d−d^- be the candidate of the previous pass, or −∞-\infty before the first pass. At the start of each pass:

(M1) each cursor e+1,…,me+1, \ldots, m is at the first posting of its list with docid greater than d−d^-;

(M2) each cursor 1,…,e1, \ldots, e is at a posting with docid at most the first docid of its list that is greater than d−d^-.

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 dd. 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 d−d^-, and dd is the least of them, so d>d−d > d^-. Line L8 moves each essential cursor at dd to the next posting, which is the first posting greater than dd. The other essential cursors are already at docids greater than dd, and since they were at the first posting greater than d−d^- and d>d−d > d^-, they are at the first posting greater than dd. So (M1) holds with dd in place of d−d^-. A nonessential cursor is either left alone, and then by (M2) it is at most the first docid greater than d−d^-, which is at most the first docid greater than dd; or line L11 moves it to the first docid at least dd, which is at most the first docid greater than dd. In both cases (M2) holds with dd. □\square

Lemma 3 (candidates and their scores). The candidates are strictly increasing. Each candidate dd that reaches line L12 is offered with s=s(d)s = s(d).

Proof. The order is the step d>d−d > d^- in the proof of Lemma 2. For the score: by (M1), an essential list contains dd if and only if its cursor is at dd, so line L8 adds the weights of exactly the essential terms that dd contains. For a nonessential cursor ii, (M2) says that it has not passed any docid greater than d−d^-, and d>d−d > d^-, so line L11 finds dd if and only if list ii contains dd. If line L10 never stops, every nonessential term is probed, and s=s(d)s = s(d). □\square

Lemma 4 (documents left out). If a matching document yy is never offered, then at some time the heap holds kk documents, each with a score at least s(y)s(y) and a docid less than yy.

Proof. There are two cases.

Case A: yy is a candidate, and line L10 stops it at index ii. At that time ss is the sum of the weights in yy of the essential terms and of the nonessential terms i+1,…,ei+1, \ldots, e, by Lemma 3. The terms 1,…,i1, \ldots, i contribute at most U1+⋯+Ui=PiU_1 + \cdots + U_i = P_i by (C1). So s(y)≤s+Pi≤θs(y) \le s + P_i \le \theta. Since i≤ei \le e and e≥1e \ge 1, the heap is full by Lemma 1.

Case B: yy is never a candidate. Take the first pass whose candidate dd is greater than yy, or, if there is none, the pass that ends in line L7 with d=∞d = \infty. Let d−d^- be the candidate before it; then d−<yd^- < y, since the candidates are increasing, none of them is yy, and dd is the first one above yy. Suppose an essential list of this pass contains yy. By (M1) its cursor is at the first posting greater than d−d^-, which is at most yy, so d≤yd \le y, which is false. So yy is only in the lists 1,…,e1, \ldots, e of this pass, and s(y)≤Pe≤θs(y) \le P_e \le \theta by (C1) and Lemma 1. Since yy matches, e≥1e \ge 1, so the heap is full.

In both cases the heap is full and each entry has a score at least θ≥s(y)\theta \ge s(y). Each entry was offered in an earlier pass, so its docid is an earlier candidate, which is less than yy in case A by Lemma 3 and at most d−<yd^- < y in case B. □\square

Theorem. Under (C1), MAXSCORE(q,k)(q, k) returns topk({(x,s(x)):x∈M})\mathrm{top}_k(\{(x, s(x)) : x \in M\}) in the order ≺\prec.

Proof. Let SS 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 topk(S)\mathrm{top}_k(S). By Lemma 4 each y∈M∖Sy \in M \setminus S ranks after kk members of SS, so topk(M)=topk(S)\mathrm{top}_k(M) = \mathrm{top}_k(S). Line L7 returns it in the order ≺\prec. ■\blacksquare

Termination. In each pass the essential cursor at dd moves one posting in line L8, so there are at most TT passes. Line L5 and the loop of line L9 do at most mm steps each.

Remark (ties). Both line L5 and line L10 use ≤θ\le \theta. A document left out with score exactly θ\theta ranks after the kk 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 s+Pis + P_i, a sum in one order, with θ\theta, 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 kk 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 TT be the total length of the mm query lists.

  • Worst case. Each pass through the loop moves at least one essential cursor by one posting, so there are at most TT passes. Each pass finds the least essential docid in O(m)O(m), does at most mm forward searches of O(log⁡T)O(\log T) each with binary search, and one heap operation of O(log⁡k)O(\log k). This gives O(T(mlog⁡T+log⁡k))O(T (m \log T + \log k)), 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. O(m+k)O(m + k) 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, kk 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 θ\theta 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 kk-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 dd, 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 θ\theta makes terms nonessential from the start.

When to use it

Use MaxScore for disjunctive queries with small kk 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 Pe≤θP_e \le \theta is unsafe.
  • Equal to the threshold. Line L5 may move a term with Pe+1≤θP_{e+1} \le \theta, and line L10 may stop with s+Pi≤θs + P_i \le \theta, 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 dd. Moving to the next posting after dd, or reusing a cursor that has already moved past dd, 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.

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
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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
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)
WritingW2 basic
  • a scene preset for the example