Algorithm Search⌘K

Data structureadvanced

Impact-ordered index

Also called score-at-a-time index, impact-sorted postings.

Sorts each posting list by precomputed impact scores, so query evaluation reads the highest impacts first and can stop early.

Time
O(n log n) buildO(T (1 + log k)) queryO(S T log k) query_with_safe_stop
Space
O(T) extraΘ(n) total
Where
S = the number of segments of the query lists; T = the total length of the query lists; k = the number of results; n = the number of postings in the index
Properties
not concurrentnot externalnot persistent

An impact-ordered index is an inverted index in which each posting list is sorted by the contribution of the term to the score, its impact, and not by docid. The impacts are computed at index time, for example from BM25, and are usually small integers. The postings of one term with the same impact form a segment, with the docids of the segment in increasing order, and the segments come in decreasing order of impact. A query is evaluated score at a time: the method reads the segments of all the query terms in one global order of decreasing impact and adds each impact into an accumulator for its document, as in term-at-a-time evaluation. The most useful postings come first, so the method can stop early. A stop with a proof that the top kk and its order cannot change is safe for the impact scores; a stop after a fixed budget of postings is approximate.

In plain words

In a normal index, each word has a list of documents in number order. Here each word has its documents grouped by how much the word counts in them, with the strongest group first. To answer a query, take the strongest group among all the query words, give its documents their points, then take the next strongest group, and so on. The leaders get most of their points early. You can stop when you can show that the rest of the groups are too weak to change the order of the leaders. Or you can stop when your time is up, and accept that the answer may be a little wrong.

The abstract type

An impact-ordered index holds, for each term tt, a sequence of segments (a1,D1),(a2,D2),…(a_1, D_1), (a_2, D_2), \ldots with integer impacts a1>a2>⋯≥1a_1 > a_2 > \cdots \ge 1 and disjoint sets of docids DjD_j. The term has impact aja_j in each document of DjD_j and does not occur in other documents. The impact score of a document xx for a query qq of mm distinct terms is the sum of the impacts of the query terms in xx. The operations are:

  • build from a docid-ordered index with weights, with a rule that maps each weight to an impact;
  • segments(t)(t), which gives the segments of tt in decreasing order of impact;
  • query(q,k)(q, k), which returns the kk documents of highest impact score, by score descending and then docid ascending, with one of three stop rules.

Representation

Each list is a sequence of segments. A segment stores its impact once and then its docids, sorted and usually compressed as gaps. The dictionary entry of a term points to its first segment and stores the number of segments. If the weights are real numbers, a quantizer maps them to integers in 1,…,L1, \ldots, L; this page uses the uniform rule a=1+⌊(L−1)w/W⌋a = 1 + \lfloor (L - 1) w / W \rfloor, where WW is the largest weight in the index. This is a form of scalar quantization. The quantized ranking is an approximation of the ranking by the real weights: documents with close weights can get the same impact, and a tie of impacts can change the order.

Operations

The query reads the segments of all query terms in one global order and keeps a map AA from docid to accumulator. For the safe stop, let rr be the sum, over the query terms, of the impact of the next unread segment of each term, or 0 for a term with none left. No document can still gain more than rr.

  1. SAAT(q, k, stop)
  2. 1G ← the segments of the query terms, sorted by impact descending, then by query position
  3. 2A ← an empty map from docid to score
  4. 3for each segment (a, D) in G do
  5. 4if stop = safe and the top k of A and its order are fixed for the gain r then break
  6. 5for each docid x in D do ▷ with stop = budget, break after the budget of postings
  7. 6A[x] ← A[x] + a, creating A[x] with 0 if needed
  8. 7return the k best entries of A, by score descending and then docid ascending

The test of line L4 needs ∣A∣≥k|A| \ge k. Let a1≥a2≥⋯a_1 \ge a_2 \ge \cdots be the sorted accumulators. The top kk and its order are fixed if ai>ai+1+ra_i > a_{i+1} + r for each i<ki < k, and ak>max⁡(ak+1,0)+ra_k > \max(a_{k+1}, 0) + r, where ak+1=0a_{k+1} = 0 if there are only kk entries. The last part also covers the documents with no accumulator yet, which can still reach at most rr.

The three stop rules are:

  • none reads every segment. It is exact for the impact scores.
  • safe stops at line L4. The returned docids and their order are exactly those of none, but the scores are lower bounds of the true impact scores, since some postings of the top kk may be unread.
  • budget stops after a fixed number of postings. It is approximate: each returned score is at most the true impact score, and the returned set can differ from the true top kk.

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) and L=8L = 8 levels. The largest weight is W=1.8592W = 1.8592, for the term binary. The query q1 "sorted array search" gives the lists:

term segments
sorted impact 4: d2; impact 3: d1, d4, d8
array impact 4: d1, d2, d8
search impact 6: d1; impact 5: d7

The global order of the segments, and the accumulators after each one:

segment d1 d2 d4 d7 d8
search 6 6
search 5 6 5
sorted 4 6 4 5
array 4 10 8 5 4
sorted 3 13 8 3 5 7

The full evaluation gives d1 13, d2 8, d8 7, d7 5, d4 3, the same order as BM25. With a budget of 4 postings and k=2k = 2, the method stops after search 6, search 5, sorted 4 and the first posting of array 4, and returns d1 10 and d7 5: d7 is in the second place, while the true second is d2. With L=4L = 4 levels, d3, d4 and d5 all get the impact score 5 for q2 "posting list merge", so the top 1 becomes d3 by the docid rule, though d4 has the best BM25 score. This is an effect of the quantization.

On the toy queries the safe stop does not save postings. An example where it does: term a has impact 9 in d1 and impact 1 in d2 and d3, term b has impact 8 in d1 and impact 2 in d4, and k=1k = 1. After the two first segments, d1 has 17 and r=1+2=3r = 1 + 2 = 3, so 17>0+317 > 0 + 3 and the method stops after 2 of 5 postings with d1.

Correctness

Each document gets exactly one impact from each query term that it contains, since the segments of a term are disjoint. With stop none, line L6 is executed once for each posting, so at the end each accumulator is the impact score of its document, and line L7 selects the top kk by the tie rule. For the safe stop, at the time of the break each unread posting of term tt has an impact at most the next unread impact of tt, so each document gains at most rr more. The gaps of more than rr in line L4 then keep the order of the top kk among themselves, and keep each of them before every other document, including the documents without an accumulator. So the docids and their order are those of the full run, while the scores are partial sums. The budget stop has no such guarantee; it only gives partial sums. The full proof is in the proof file.

Proof: Score-at-a-time evaluation is exact without a stop and order-exact with the safe stopfull

All statements are about the impact scores: s(x)s(x) is the sum of the impacts of the query terms in xx, and MM is the set of documents that contain a query term. Whether the impact ranking agrees with a ranking by real weights depends on the quantizer and is not claimed here. 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. The impacts are positive integers, so all sums are exact.

Lemma 1 (partial sums). After any number of segments of GG have been read in full, A[x]A[x] exists if and only if a read segment contains xx, and then A[x]A[x] is the sum of the impacts of the read segments that contain xx. Each term contributes at most one read segment to this sum.

Proof. Line L6 adds aa once for each docid of a read segment. The segments of one term are disjoint, so xx is in at most one segment of each term, and that segment carries the impact of the term in xx. □\square

Theorem 1 (stop none). SAAT(q,k,none)(q, k, \mathit{none}) returns topk({(x,s(x)):x∈M})\mathrm{top}_k(\{(x, s(x)) : x \in M\}) in the order ≺\prec.

Proof. All segments of the query terms are read. By Lemma 1, AA maps each x∈Mx \in M to the sum of the impacts of all query terms in xx, which is s(x)s(x), and has no other entries. Line L7 selects the top kk by ≺\prec. □\square

Lemma 2 (the remaining gain). At the test of line L4, let rr be the sum, over the query terms, of the impact of the next unread segment of the term, or 0 if the term has none left. Then each document xx has A[x]≤s(x)≤A[x]+rA[x] \le s(x) \le A[x] + r, with A[x]=0A[x] = 0 if xx has no entry.

Proof. The lower bound is Lemma 1, since impacts are positive. For the upper bound, the impacts of xx that are not yet added come from unread segments, at most one for each term. The segments of a term come in decreasing order of impact, and GG reads the segments of each term in this order, so each unread segment of a term has an impact at most the impact of its next unread segment. Summing over the terms gives at most rr. □\square

Theorem 2 (stop safe). Let SAAT(q,k,safe)(q, k, \mathit{safe}) return the list (x1,b1),…,(xj,bj)(x_1, b_1), \ldots, (x_j, b_j), and let SAAT(q,k,none)(q, k, \mathit{none}) return (y1,s1),…,(yj′,sj′)(y_1, s_1), \ldots, (y_{j'}, s_{j'}). Then j=j′j = j', xi=yix_i = y_i for each ii, and bi≤s(xi)=sib_i \le s(x_i) = s_i.

Proof. If line L4 never breaks, the run is the run of stop none, and Theorem 1 applies with bi=sib_i = s_i.

Otherwise let the break happen with the accumulators AA and gain rr. The test needs ∣A∣≥k|A| \ge k, so j=kj = k; also ∣M∣≥∣A∣≥k|M| \ge |A| \ge k, so j′=kj' = k. Let a1≥⋯≥aka_1 \ge \cdots \ge a_k be the kk best accumulators, by ≺\prec, of the documents x1,…,xkx_1, \ldots, x_k, and let ak+1a_{k+1} be the next one, or 0. The test says ai>ai+1+ra_i > a_{i+1} + r for i<ki < k and ak>max⁡(ak+1,0)+ra_k > \max(a_{k+1}, 0) + r.

For i<ki < k, Lemma 2 gives s(xi)≥ai>ai+1+r≥s(xi+1)s(x_i) \ge a_i > a_{i+1} + r \ge s(x_{i+1}). So s(x1)>s(x2)>⋯>s(xk)s(x_1) > s(x_2) > \cdots > s(x_k).

Let zz be any other document of MM. Either it has an entry, which is at most ak+1a_{k+1}, or it has none, and then its entry is taken as 0. In both cases s(z)≤max⁡(ak+1,0)+r<ak≤s(xk)s(z) \le \max(a_{k+1}, 0) + r < a_k \le s(x_k).

So x1,…,xkx_1, \ldots, x_k are the kk documents of highest true score, all with distinct scores, and every other document has a strictly lower score. The tie rule is never needed, and topk(M)\mathrm{top}_k(M) is x1,…,xkx_1, \ldots, x_k in this order, which is the output of stop none by Theorem 1. The returned scores are bi=ai≤s(xi)b_i = a_i \le s(x_i) by Lemma 2. ■\blacksquare

Proposition 3 (stop budget). Each pair (x,b)(x, b) returned by SAAT(q,k,budget)(q, k, \mathit{budget}) has b≤s(x)b \le s(x), and with a budget of at least the total length TT of the query lists, the output equals that of stop none.

Proof. The accumulators are partial sums of the read postings, so b≤s(x)b \le s(x) as in Lemma 2. A budget of at least TT never breaks the loop, so the run is that of stop none. □\square

No more is claimed for the budget stop. With a smaller budget the returned set can differ from the true top kk, as the toy example on the page shows.

Remark (strictness). Theorem 2 needs strict gaps. With ak=ak+1+ra_k = a_{k+1} + r, the document zz of ak+1a_{k+1} could end with s(z)=s(xk)s(z) = s(x_k) and a smaller docid, and it would then rank before xkx_k.

Remark (real weights). With real weights in place of integer impacts, Lemma 2 still holds in exact arithmetic. In floating point, the sums A[x]A[x] are added in impact order, not in query order, so they can differ in the last bit from the scores of a docid-ordered scan.

Complexity

The model is the word RAM. Let nn be the number of postings in the index and TT the total length of the query lists.

  • Build. Sorting each list by impact costs O(nlog⁡n)O(n \log n) in total, or O(n+L)O(n + L) for each list with a bucket for each impact level.
  • Full query. TT accumulator updates, O(1)O(1) expected each with a hash table or O(1)O(1) with an array of NN accumulators, plus O(Tlog⁡k)O(T \log k) to select the top kk.
  • Safe stop. The check in line L4 is done before each of the SS segments. Done by selecting the best k+1k+1 accumulators, it costs O(Tlog⁡k)O(T \log k) each time, so O(STlog⁡k)O(S T \log k) in the worst case. Practical systems check less often or keep the leaders in a small structure.
  • Budget stop. At most the budget of postings, so the query time has a bound that does not depend on the list lengths.
  • Space. Θ(n)\Theta(n) for the index and O(T)O(T) for the accumulators.

Variants

  • Docid order. A docid-ordered index supports document-at-a-time evaluation with WAND or block-max WAND. An impact-ordered index gives up the docid order, so these methods do not apply.
  • Frequency-sorted lists. Persin, Zobel and Sacks-Davis (1996) sorted each list by term frequency, an earlier form of the same idea, and skipped postings below thresholds set during the query.
  • Phases of Anh and Moffat. Anh and Moffat (2006) process the segments in impact order and use the bounds to stop creating new accumulators and then to stop the evaluation.
  • Anytime ranking. Lin and Trotman (2015) stop after a fixed number of postings, so that the query time has a bound, and accept an approximate answer.
  • Tiers. A tiered index cuts each list into a few coarse tiers by weight; this is a coarse impact order.

When to use it

Use an impact-ordered index when the query time must have a fixed bound, as in anytime ranking, or when long queries make the many cursors of DAAT costly. It needs integer impacts fixed at index time, so the scoring function cannot change at query time without a rebuild. Crane and others (WSDM 2017) compared score-at-a-time evaluation with WAND and block-max WAND on the same collections; the results are measurements, and which method is faster depends on the query length, kk and the collection.

Pitfalls

  • Quantization is not free. Too few levels make ties, and a tie can change the ranking. The exact result of score-at-a-time evaluation is exact for the impacts, not for the real weights.
  • Wrong bound for the gain. The value rr must use the next unread impact of every query term, not only of the current one, and must count a term once even when it has many unread segments, since a document is in at most one segment of each term.
  • Ties at the stop. The gaps in line L4 must be strictly greater than rr. A gap equal to rr can close, and then the docid rule decides, which the partial scores do not show.
  • Reporting partial scores. After a safe stop, the scores are lower bounds. Code that uses them as the true scores, for example to merge with another shard, gets them wrong.
  • Budget results called exact. With a budget stop the result is approximate and must be reported so.

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.

impact_ordered_index.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/impact-ordered-index/. The authors are listed in prov/BBYS9T.jsonl.
"""An impact-ordered index and score-at-a-time (SAAT) query evaluation.

A document-ordered index maps each term to a list of (docid, weight)
pairs in increasing docid order. The impact-ordered index stores, for each
term, a list of segments (impact, docids): the impact is a positive
integer, the docids of a segment are in increasing order, and the segments
are in decreasing order of impact. The score of a document is the sum of
the impacts of the query terms that it contains.

saat reads the segments of all query terms in one global order: impact
descending, then query position. It adds each impact to an accumulator.
It has three stop rules:

  "none"    read every segment. Safe: the exact top k.
  "safe"    stop when the top k documents and their order are fixed. The
            docids and their order are exact; the scores returned are lower
            bounds of the true scores.
  "budget"  stop after a fixed number of postings (anytime ranking). This
            is approximate: each score is the sum of the postings read so
            far, which is at most the true score.
"""

import heapq
import math


class Stats:
    """Work counters: accumulators created and postings read."""

    def __init__(self):
        self.scored = 0
        self.postings = 0


def build(index, levels=None):
    """Build an impact-ordered index from a document-ordered one.

    With levels = None the weights must already be positive integers, and
    they are the impacts. Otherwise each weight w becomes the impact
    1 + floor((levels - 1) * w / W), where W is the largest weight in the
    index, so the impacts are in 1..levels.
    """
    top = max((w for p in index.values() for _, w in p), default=0)
    impacts = {}
    for t, plist in index.items():
        groups = {}
        for d, w in plist:
            if levels is None:
                if w != int(w) or w < 1:
                    raise ValueError("impacts must be positive integers")
                a = int(w)
            else:
                a = 1 + math.floor((levels - 1) * w / top) if top > 0 else 1
            groups.setdefault(a, []).append(d)
        impacts[t] = [(a, groups[a]) for a in sorted(groups, reverse=True)]
    return impacts


def to_document_order(impacts):
    """The document-ordered index with the impacts as weights."""
    index = {}
    for t, segs in impacts.items():
        index[t] = sorted((d, a) for a, ids in segs for d in ids)
    return index


def ranked(acc, n):
    """The n best (docid, score) pairs of the accumulators, by the tie rule."""
    return heapq.nsmallest(n, acc.items(), key=lambda p: (-p[1], p[0]))


def order_is_fixed(acc, k, rest):
    """True when no further postings can change the top k or its order.

    rest bounds the score that any document can still gain. Each of the top
    k must beat the next one by more than rest, and the k-th must beat every
    other document, including those with no accumulator yet, by more than
    rest.
    """
    if len(acc) < k:
        return False
    best = ranked(acc, k + 1)
    for i in range(k - 1):
        if best[i][1] <= best[i + 1][1] + rest:
            return False
    below = best[k][1] if len(best) > k else 0
    return best[k - 1][1] > max(below, 0) + rest


def saat(impacts, query, k, stop="none", budget=0):
    """Return (the top k as a list of (docid, score), Stats)."""
    stats = Stats()
    if k <= 0:
        return [], stats
    lists = [impacts.get(t, []) for t in query]
    segs = sorted(  # @line L1
        (-a, pos, j) for pos, plist in enumerate(lists) for j, (a, _) in enumerate(plist)
    )
    nxt = [plist[0][0] if plist else 0 for plist in lists]  # next unread impact
    acc = {}  # @line L2
    for neg_a, pos, j in segs:  # @line L3
        if stop == "safe" and order_is_fixed(acc, k, sum(nxt)):  # @line L4
            break
        a = -neg_a
        for d in lists[pos][j][1]:  # @line L5
            if stop == "budget" and stats.postings >= budget:
                break
            stats.postings += 1
            acc[d] = acc.get(d, 0) + a  # @line L6
        if stop == "budget" and stats.postings >= budget:
            break
        nxt[pos] = lists[pos][j + 1][0] if j + 1 < len(lists[pos]) else 0
    stats.scored = len(acc)
    return ranked(acc, k), stats  # @line L7


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
irtoy.py 76 lines
# 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
test_impact_ordered_index.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/impact-ordered-index/. The authors are listed in prov/BBYS9T.jsonl.

import random

import irtoy
from impact_ordered_index import bm25_index, build, exhaustive_top_k, saat, to_document_order


def toy_index():
    return bm25_index({d: irtoy.tokenize(t) for d, t in irtoy.DOCS.items()})


def random_index(rng, n, vocab):
    """A random index on docids 1..n with integer impacts 1..9."""
    index = {}
    for t in range(vocab):
        density = rng.random() ** 2
        ids = [d for d in range(1, n + 1) if rng.random() < density]
        index[f"t{t}"] = [(d, rng.randint(1, 9)) for d in ids]
    return index


def test_toy_quantized():
    index = toy_index()
    q1 = irtoy.tokenize(irtoy.QUERIES["q1"])
    q2 = irtoy.tokenize(irtoy.QUERIES["q2"])
    imp = build(index, 8)
    assert imp["search"] == [(6, [1]), (5, [7])]
    assert imp["sorted"] == [(4, [2]), (3, [1, 4, 8])]
    got, stats = saat(imp, q1, 5)
    assert got == [(1, 13), (2, 8), (8, 7), (7, 5), (4, 3)]
    assert stats.postings == 9 and stats.scored == 5
    # With 8 levels the ranking of q1 and q2 is the BM25 ranking.
    for q in (q1, q2):
        assert [d for d, _ in saat(imp, q, 5)[0]] == [d for d, _ in exhaustive_top_k(index, q, 5, irtoy.DOCS)]
    # With 4 levels d3, d4 and d5 all get 5 for q2, so d3 ranks first,
    # though d4 has the best BM25 score.
    assert saat(build(index, 4), q2, 1)[0] == [(3, 5)]


def test_safe_stop_example():
    imp = {"a": [(9, [1]), (1, [2, 3])], "b": [(8, [1]), (2, [4])]}
    got, stats = saat(imp, ["a", "b"], 1, stop="safe")
    # After two segments d1 has 17, and any document can still gain at most
    # 1 + 2 = 3.
    assert got == [(1, 17)] and stats.postings == 2
    assert saat(imp, ["a", "b"], 1)[0] == [(1, 17)]
    assert saat(imp, ["a", "b"], 3)[0] == [(1, 17), (4, 2), (2, 1)]


def test_build_rejects_bad_impacts():
    for bad in (0, 2.5):
        try:
            build({"a": [(1, bad)]})
        except ValueError:
            pass
        else:
            raise AssertionError("expected ValueError")


def test_edges():
    imp = {"a": [(3, [1]), (1, [4])], "b": [(2, [4])]}
    for stop in ("none", "safe"):
        assert saat(imp, [], 3, stop)[0] == []
        assert saat(imp, ["a"], 0, stop)[0] == []
        assert saat(imp, ["zz"], 3, stop)[0] == []
        assert saat(imp, ["a", "b"], 1, stop)[0] == [(1, 3)]
        assert saat(imp, ["a", "b"], 5, stop)[0] == [(1, 3), (4, 3)]
    assert saat(imp, ["a", "b"], 5, "budget", 0)[0] == []


def test_random():
    rng = random.Random(20251120)
    saved = 0
    for trial in range(300):
        n = rng.randint(1, 200)
        index = random_index(rng, n, 8)
        imp = build(index)
        assert to_document_order(imp) == index
        q = rng.sample(sorted(index), rng.randint(1, 5))
        if rng.random() < 0.2:
            q.append("missing")
        k = rng.randint(1, 12)
        total = sum(len(index.get(t, [])) for t in q)
        union = len({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)))
        # Run to the end: safe and exact.
        got, stats = saat(imp, q, k)
        assert got == want
        assert stats.postings == total and stats.scored == union
        # Safe early stop: exact docids in exact order, lower-bound scores.
        got, stats = saat(imp, q, k, "safe")
        assert [d for d, _ in got] == [d for d, _ in want]
        assert all(s <= true[d] for d, s in got)
        assert stats.postings <= total and stats.scored <= union
        saved += total - stats.postings
        # Budget stop: approximate; each score is at most the true score.
        budget = rng.randint(0, total)
        got, stats = saat(imp, q, k, "budget", budget)
        assert stats.postings == budget
        assert len(got) <= k and all(s <= true[d] for d, s in got)
        assert saat(imp, q, k, "budget", total)[0] == want
    assert saved > 0

History

Persin, Zobel and Sacks-Davis (1996) used frequency-sorted indexes for filtered retrieval. Anh and Moffat developed impact-ordered indexes with integer impacts, and in 2006 they gave pruned score-at-a-time evaluation with early stopping. Lin and Trotman (2015) gave anytime ranking with a fixed budget of postings in the JASS system, and Crane and others (2017) compared score-at-a-time and document-at-a-time evaluation by experiments.

References

  1. Vo Ngoc Anh and Alistair Moffat, Pruned query evaluation using pre-computed impacts, SIGIR 2006, the impact-ordered index with integer impacts in segments, score-at-a-time evaluation, and the stop rules that end the evaluation early
  2. Jimmy Lin and Andrew Trotman, Anytime ranking for impact-ordered indexes, ICTIR 2015, score-at-a-time evaluation with a fixed budget of postings, so that the query time has a bound
  3. Matt Crane, J. Shane Culpepper, Jimmy Lin, Joel Mackenzie and Andrew Trotman, A comparison of document-at-a-time and score-at-a-time query evaluation, WSDM 2017, the experiments that compare score-at-a-time evaluation on an impact-ordered index with WAND and block-max WAND on a docid-ordered index
  4. Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 7, Section 7.1.5 (impact ordering)

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.build
  • a full proof of time.query
  • a full proof of time.query_with_safe_stop
  • a full proof of space.extra
  • a full proof of space.total
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/BBYS9T/text.yaml