Algorithmcore
Document-at-a-time evaluation
Also called DAAT.
Reads all query posting lists in parallel in docid order and scores each document fully before moving on, keeping a heap of the best k.
- Solves
- Ranked retrieval
- Time
- O(T (m + log k)) worstO(T (log m + log k)) with_cursor_heap
- 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
Document-at-a-time evaluation, or DAAT, answers a ranked retrieval query from an inverted index. It opens one cursor on the posting list of each query term and moves all cursors forward together in increasing document id order. At each step it takes the smallest document id under any cursor, adds the weights of all terms whose cursor is at that id, and so finishes the score of that document before it looks at the next one. A min-heap of size keeps the best documents seen so far. DAAT reads every posting of every query list and scores every matching document, so it is the baseline that the dynamic pruning methods WAND, MaxScore and block-max WAND improve on. The other basic strategy is term-at-a-time evaluation, which reads one whole list after the other and keeps a partial score for each document.
In plain words
Each word of the query has a list of the documents that contain it, sorted by document number. Put a finger on the first entry of each list. The smallest number under your fingers is the next document to look at. Add up what each word that has this document gives to its score, move those fingers one step, and the document is done: its score is final. Keep a short table of the best few documents seen so far. A new document goes into the table only if it is better than the worst one there. When all fingers fall off their lists, the table holds the answer. The work grows with the total length of the lists, and only a few numbers are kept in memory at any time.
The problem
The input is a query of distinct terms, the posting list of each term, and a number . A posting is a pair of a document id and a weight , the contribution of the term to the score of , for example a BM25 term weight. Each list is in strictly increasing order of . The score is the sum of the weights of the query terms that contains. A document matches if it contains at least one query term. The output is the matching documents of highest score, or all of them if fewer than match, ranked by score descending and then by document id ascending. This is the tie rule of this area. A term with no posting list has an empty list.
The algorithm
Each cursor points into list . It reports , which is when the cursor is past the end, and , and it moves with .
DAAT(q, k) ▷ q has m terms, each with a sorted list- 1
for i ← 1 to m do c_i ← a cursor at the start of list i - 2
H ← an empty min-heap of (score, docid) pairs - 3
d ← min over i of c_i.docid - 4
while d < ∞ do - 5
s ← 0 - 6
for i ← 1 to m do - 7
if c_i.docid = d then s ← s + c_i.weight, c_i.next() - 8
if |H| < k then insert (s, d) into H else if s > the least score in H then replace the least entry of H by (s, d)- 9
d ← min over i of c_i.docid - 10
return the entries of H, by score descending and then docid ascending
The heap orders its entries by score and, among equal scores, puts the larger docid lower, so its least entry is the one that the tie rule ranks last. Line L8 replaces it only on a strictly greater score. Line L7 adds the weights in query order, the same order as an exhaustive scan, so with floating-point weights the scores agree to the last bit.
Example
Take the toy collection of this area with BM25 weights (, , the Lucene IDF , , ), the query q1 "sorted array search" and . The lists are, with weights rounded to 4 places:
- sorted: d1 0.7192, d2 0.9497, d4 0.6896, d8 0.6896
- array: d1 0.98, d2 0.9396, d8 0.9396
- search: d1 1.3291, d7 1.2743
| step | terms at | line L8 | after | ||
|---|---|---|---|---|---|
| 1 | 1 | sorted, array, search | 3.0283 | insert | d1 3.0283 |
| 2 | 2 | sorted, array | 1.8893 | insert | d1 3.0283, d2 1.8893 |
| 3 | 4 | sorted | 0.6896 | not greater than 1.8893 | unchanged |
| 4 | 7 | search | 1.2743 | not greater than 1.8893 | unchanged |
| 5 | 8 | sorted, array | 1.6292 | not greater than 1.8893 | unchanged |
After step 5 every cursor is at . The answer is d1 3.0283, d2 1.8893. DAAT read all 9 postings and scored all 5 matching documents. For it returns d1, d2, d8, d7, d4 with the scores 3.0283, 1.8893, 1.6292, 1.2743, 0.6896, the same as scoring every document. For q2 "posting list merge", d3 and d5 both score 2.2139; d3 comes first in docid order and enters the heap first, and d5 cannot push it out, so the ranking is d4, d3, d5, as the tie rule asks.
Correctness
Before each test of line L4, two facts hold. First, each cursor is at the first posting of list with docid at least , and is the least docid under any cursor; so each matching document less than has been scored, and no document between two consecutive values of matches. Second, each scored document got its exact score, because when is processed every list that contains has its cursor on . The heap rule keeps the top of the documents scored so far by the tie rule: documents arrive in increasing docid order, so a new document with a score equal to the least score in has a larger docid than every entry and ranks below them all, and line L8 is right to keep it out. When the loop ends every matching document has been scored, so is the top . The full proof is in the proof file.
Proof: DAAT returns the exact top k under the tie rulefull
Write for the rank order of this area: , read "ranks before", if , or and . It is a strict total order on pairs with distinct docids. For a finite set of pairs, is the set of the first pairs of in this order. The weights are exact numbers (integers, fractions or reals); the remark at the end covers floating point.
Lemma 1 (the heap rule). Let be a set of pairs whose docids are all less than , and let . Offer by line L8. Then the new heap is .
Proof. If , then , so and its top is all of it, which is plus the new pair. Line L8 inserts the pair.
Else . Let be the last pair of in the order ; it has the least score in and, among pairs of that score, the largest docid, which is how the heap orders its entries. Since , the new pair ranks before if and only if . If , then the new pair ranks before , and every pair of ranks after , so the first pairs of are plus . Line L8 makes exactly this replacement. If , then ranks after , so is still the top , and line L8 leaves unchanged.
Invariant. Let be the set of matching documents, and for each document let be its score. Before each test of line L4:
(D1) Each cursor is at the first posting of list whose docid is at least , and .
(D2) .
Initialization. Line L1 puts each cursor at the start of its list, so (D1) holds with from line L3. No document is less than the least docid of all lists, so the set in (D2) is empty, and is empty.
Maintenance. Assume (D1) and (D2) and . In lines L6 and L7, a list contains if and only if its cursor is at , by (D1): the cursor is at the first posting with docid at least , and that posting has docid exactly when the list contains . So line L7 adds the weight of each query term that contains and no other weight, and after the loop. The document matches, since some cursor is at . Line L7 moves each cursor at one step, so after line L6 each cursor is at the first posting with docid greater than . Let be the value from line L9. No list has a posting with docid strictly between and , so no document strictly between them matches. By Lemma 1, after line L8, , which is the set of (D2) for . Each cursor is at the first posting with docid greater than , which is the first with docid at least , so (D1) holds for .
Termination. Each iteration moves at least one cursor one step, and there are postings, so the loop runs at most times.
Theorem. DAAT returns in the order : the exact top with the tie rule of score descending, then docid ascending.
Proof. At the end , so by (D2) is the top of all matching documents. Line L10 sorts it by .
Remark (floating point). With floating-point weights the theorem holds for the scores computed in query order, which is the order of line L7 and of the exhaustive reference scan. The two methods then compute the same sums, bit for bit, and so return the same ranking. A method that adds the same weights in another order can get a sum that differs in the last bit, and then a near tie can break the other way.
Complexity
Let be the total length of the query lists, and let the cost model be the word RAM with an in-memory index.
- Postings read. Exactly . Each posting is read once in line L7, and each iteration of line L4 reads at least one.
- Documents scored. Exactly the number of matching documents, which is at most . DAAT has no way to skip a document.
- Time. Lines L3, L6 and L9 scan the cursors, so each iteration costs , and the heap costs . With at most iterations the time is . With the cursors in a second heap keyed by docid, the minimum costs for each posting, and the time is .
- Space. besides the index: one cursor for each term and the heap. This is the main advantage over term-at-a-time evaluation, which keeps one accumulator for each matching document.
- On disk. The lists are read in order, but of them at once, so each list needs its own read buffer.
Properties
- Exact. It returns the same top , scores and order as scoring every document, for any nonnegative or even negative weights, since it never uses a bound.
- Small memory. Only the cursors and the heap, independent of the number of matching documents.
- Each score is final when computed. This allows the threshold tests of WAND and MaxScore, which compare a bound on a whole document with the least score in the heap.
- Sequential access only. Each list is read from left to right, which suits compressed lists that decode in order.
Variants and improvements
- Boolean AND. Score only if all cursors are at , and move the others to with a forward search. This is a k-way form of list intersection.
- MaxScore. Splits the terms by their upper bounds and never starts a document from the lists of terms that cannot lift it into the top alone.
- WAND. Keeps the cursors sorted by docid and jumps to the first document whose summed term upper bounds exceed the threshold.
- Block-max WAND. Adds an upper bound for each block of postings, so it skips whole blocks.
- Cursor heap. A heap of cursors replaces the linear scan for long queries.
- Score-at-a-time. An impact-ordered index gives up docid order, and with it the DAAT structure.
When to use it
Use DAAT when the index is in docid order and memory for accumulators is short, or as the base of a dynamic pruning method. Plain DAAT is the right choice for short lists or when is close to the number of matching documents, since then no pruning method can skip much. For long lists and small , use WAND, block-max WAND or MaxScore on the same index.
Pitfalls
- Replacing on equal scores. If line L8 used "at least" in place of "greater than", d5 would push out d3 in q2 with , and the result would break the tie rule.
- Forgetting to advance. Each cursor that is at must move in line L7. A cursor left behind makes line L9 return again and the loop never ends.
- Different summation order. With floats, adding the weights in cursor order and not in query order can change the last bit of a score, and then a tie may break the other way than in the exhaustive scan.
- Missing terms. A term with no list must give a cursor at , not an error.
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
# Part of https://algorithm.tamnd.com/document-at-a-time-evaluation/. The authors are listed in prov/CR25E3.jsonl.
"""Document-at-a-time (DAAT) evaluation of a ranked query.
An index maps each term to its posting list: a list of (docid, weight)
pairs in increasing docid order. The weight is the contribution of the
term to the score of the document, for example a BM25 term weight. The
score of a document for a query is the sum of the weights of the query
terms that it contains, added in query order. A document matches when it
contains at least one query term. Results rank by score descending, then
by docid ascending.
"""
import heapq
import math
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."""
def __init__(self, postings, stats):
self.ids = [d for d, _ in postings]
self.ws = [w for _, w in postings]
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
class TopK:
"""The best k (docid, score) pairs seen so far.
The heap holds (score, -docid), so its minimum is the entry of lowest
score and, among equal scores, of largest docid: the entry that the
tie rule ranks last. A new document replaces it only on a strictly
greater score. Documents arrive in increasing docid order, so an equal
score never displaces a smaller docid.
"""
def __init__(self, k):
self.k = k
self.heap = []
def offer(self, d, s):
if len(self.heap) < self.k:
heapq.heappush(self.heap, (s, -d))
return True
if s > self.heap[0][0]:
heapq.heapreplace(self.heap, (s, -d))
return True
return False
def result(self):
return sorted(((-nd, s) for s, nd in self.heap), key=lambda p: (-p[1], p[0]))
def daat(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] # @line L1
top = TopK(k) # @line L2
d = min((c.docid() for c in cursors), default=END) # @line L3
while d != END: # @line L4
s = 0 # @line L5
for c in cursors: # @line L6
if c.docid() == d: # @line L7
s = s + c.weight()
c.next()
stats.scored += 1
top.offer(d, s) # @line L8
d = min(c.docid() for c in cursors) # @line L9
return top.result(), stats # @line L10
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]
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_document_at_a_time_evaluation.py 84 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/document-at-a-time-evaluation/. The authors are listed in prov/CR25E3.jsonl.
import random
from fractions import Fraction
import irtoy
from document_at_a_time_evaluation import bm25_index, daat, exhaustive_top_k
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_check_values():
index = toy_index()
got, stats = daat(index, irtoy.tokenize(irtoy.QUERIES["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 and stats.postings == 9
# q2: d3 and d5 tie at 2.2139; the smaller docid ranks first.
got, _ = daat(index, irtoy.tokenize(irtoy.QUERIES["q2"]), 3)
assert [d for d, _ in got] == [4, 3, 5]
assert got[1][1] == got[2][1]
# q4: no query term occurs in the collection.
assert daat(index, irtoy.tokenize(irtoy.QUERIES["q4"]), 5)[0] == []
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, _ = daat(index, q, k)
assert got == exhaustive_top_k(index, q, k, irtoy.DOCS)
def test_edges():
index = {"a": [(1, 3), (4, 1)], "b": [(4, 2)]}
assert daat(index, [], 3)[0] == []
assert daat(index, ["a"], 0)[0] == []
assert daat(index, ["zz"], 3)[0] == []
# d1 and d4 both score 3, so d1 ranks first.
assert daat(index, ["a", "b"], 1)[0] == [(1, 3)]
assert daat(index, ["a", "b"], 5)[0] == [(1, 3), (4, 3)]
# Equal scores: the smaller docid wins the last place.
assert daat({"a": [(1, 3), (2, 3), (3, 3)]}, ["a"], 2)[0] == [(1, 3), (2, 3)]
def test_random_against_exhaustive():
rng = random.Random(20251115)
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 = daat(index, q, k)
assert got == exhaustive_top_k(index, q, k, range(1, n + 1))
union = set()
for t in q:
union.update(d for d, _ in index.get(t, []))
# DAAT scores every matching document once and reads every posting.
assert stats.scored == len(union)
assert stats.postings == sum(len(index.get(t, [])) for t in q)
History
Turtle and Flood (1995) named and compared the two classic evaluation strategies, term-at-a-time and document-at-a-time, and gave a max_score optimization for each. Moffat and Zobel (1996) studied the term-at-a-time side with limited accumulators and skips. Broder and others (2003) built WAND on the document-at-a-time strategy, and most later dynamic pruning methods, such as block-max WAND (Ding and Suel 2011), also process one document at a time.
References
- Howard Turtle and James Flood, Query evaluation, strategies and optimizations, Information Processing and Management 31(6), 1995, 831-850, the term-at-a-time and document-at-a-time evaluation strategies and their cost, and the max_score optimization for each
- Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 6, Section 6.3.3 (computing vector scores with accumulators) and Chapter 7, Section 7.1 (efficient scoring and ranking, with the heap for the top k)
- Stefan Buettcher, Charles L. A. Clarke and Gordon V. Cormack, Information Retrieval, Implementing and Evaluating Search Engines, MIT Press, 2010, Chapter 5, query processing for ranked retrieval (document-at-a-time and term-at-a-time methods)
- 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 query processing, with document-at-a-time and term-at-a-time traversal and the dynamic pruning methods built on them
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag CR25E3 Edit this page History Report an error Markdown