Algorithmadvanced
CORI resource selection
Also called collection retrieval inference network.
Ranks the collections of a federated search system for a query by a tf-idf style belief computed from each collection's document frequencies and size.
- Solves
- Federated search
- Time
- O(K m + K log K) expected
- Space
- O(K) extra
- Where
- K = the number of collections; m = the number of query terms
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- James P. Callan, Zhihong Lu, W. Bruce Croft, 1995
CORI resource selection is a method that ranks the collections of a federated search system for a query, so that the broker sends the query only to the best few. James Callan, Zhihong Lu and Bruce Croft introduced it in 1995 as the collection retrieval inference network. It treats each collection as one large document: the document frequency of a term in the collection plays the part of the term frequency, and the number of collections that contain the term plays the part of the document frequency of tf-idf. The belief formula has three constants, 50, 150 and , that were fitted on test data and not derived.
In plain words
A search broker can send a query to many separate search engines, but asking all of them is slow and costly. So it keeps a short summary of each engine: how many documents it has with each word, and how big it is. For a new query, it gives each engine a score. An engine scores high for a word when many of its documents contain the word, after a correction for the size of the engine. A word that only a few engines have counts more than a word that every engine has. The score of an engine is the average over the query words, and every word adds at least a fixed base amount. The broker then asks only the few engines with the best scores.
The problem
There are collections , each behind its own search engine. The broker has a description of each collection: , the number of documents of that contain the term , and , the number of tokens in (the papers call it the number of words). Let be the mean of the , and let be the number of collections that contain . The CORI papers call the collection frequency, but on this site means the number of occurrences of in a collection, so this page writes . A query is a bag of terms. The task is to rank the collections by their expected value for and return the top , with ties broken by the smaller collection number.
This is the resource selection step of federated search. Building the descriptions (by cooperation, or by query-based sampling when the engines do not cooperate) and merging the result lists are separate steps.
The algorithm
For a term with , the belief that collection satisfies is
with , the default belief. is a ratio of two logarithms, so the base does not matter. The score of the collection is the mean belief over the query terms, the #sum operator of the inference network:
CORI-SELECT(q, C_1, ..., C_K, n) ▷ b = 0.4- 1
for each collection i: cw_i ← number of tokens in C_i - 2
avg ← (cw_1 + ... + cw_K) / K - 3
for each distinct query term t: c(t) ← number of i with df_i(t) > 0 - 4
for each collection i: - 5
s_i ← 0 - 6
for each query term t, repeats included: - 7
if c(t) = 0 then s_i ← s_i + b; continue - 8
T ← df_i(t) / (df_i(t) + 50 + 150 · cw_i / avg) - 9
I ← log((K + 0.5) / c(t)) / log(K + 1.0) - 10
s_i ← s_i + b + (1 - b) · T · I - 11
s_i ← s_i / m - 12
return the n collections with the largest s_i, ties to the smaller i
A term that no collection contains adds to every score, so it does not change the ranking; line L7 states this rule, which the formula leaves open because is undefined when . Lines L1 to L3 depend only on the descriptions and the query terms, so a broker computes and once and from a term dictionary.
Example
Split the eight documents of the shared toy collection of the information retrieval pages into three collections: (searching and sorting arrays), (posting lists) and . Tokens are the lower-case words. Then , and .
Take q1, "sorted array search". The term "array" is in the three documents of and in no other collection, so and . For , , so and . The term "sorted" is in (3 documents) and (1 document), and "search" in and (1 document each), so for both and .
| collection | sorted | array | search | score for q1 |
|---|---|---|---|---|
| 0.403330 | 0.407455 | 0.401120 | 0.403969 | |
| 0.401092 | 0.400000 | 0.400000 | 0.400364 | |
| 0.400000 | 0.400000 | 0.401469 | 0.400490 |
The ranking is , , . beats because it is smaller: each has one document with one of the rarer query terms, and the size correction favours . For q2, "posting list merge", the scores are , and , so comes first. For q4, "quantum circuit", no collection has a query term, every score is , and the tie rule gives , , .
All the scores stay close to , because the constants 50 and 150 assume collections with thousands of documents: here is small next to them. If each collection holds 1000 copies of its documents, the scores for q1 become about , and , with the same order.
Correctness
CORI is a scoring formula, so correctness means that the procedure computes the formula and that the formula behaves as its authors intend. The file proofs/correctness.md proves both. Each belief lies in , because and when . The belief grows strictly with , falls with the size , and the factor falls as more collections contain the term. For a one-term query, and are the same for every collection, so the ranking depends only on and . The factor is the term frequency part of BM25 divided by , with and a length weight of (the BM25 parameter usually called , not the default belief of this page), because . Whether the top collections hold the most relevant documents is a measured property, not a theorem.
Proof: CORI computes its belief formula, and each belief lies between b and 1full
There are collections . For collection and term , is the number of documents of that contain , and is the number of tokens of . Let , and let be the number of collections that contain . The constants are , and . For ,
and when . For a query with terms, repeats kept, the score is .
Theorem 1 (the procedure computes the formula). Lines L1 to L11 set to the score above for every , and line L12 returns the indexes with the largest scores, ties to the smaller index.
Proof. Lines L1 and L2 compute and from the descriptions, and line L3 computes for each distinct query term. For a fixed , the loop of lines L6 to L10 keeps the invariant that after terms, : line L7 adds when , and lines L8 to L10 add otherwise. Line L11 divides by . Line L12 sorts by the key , which puts larger scores first and, among equal scores, smaller indexes first, and keeps the first .
Lemma 2 (base of the logarithm). is the same for every base of the logarithm.
Proof. , so the factor appears in the numerator and the denominator and cancels.
Theorem 3 (range). For every collection and term, . So every score lies in .
Proof. If , . Else and the denominator of exceeds by at least , so . Since , the ratio lies in . The lower end is greater than and the upper end is less than , so and . Then and . A mean of numbers in lies in .
Theorem 4 (monotonicity). Fix the term and all other statistics. Then strictly increases with and strictly decreases with (when , keeping fixed). strictly decreases with .
Proof. Write with and . For , . For fixed , falls when grows, and grows with . The factor is positive by Theorem 3, so moves in the same direction as . The numerator of is the logarithm of a value that falls when grows, and the denominator does not depend on .
Consequence. For a one-term query, and are the same for every collection, so the ranking of the collections is the ranking by : it depends only on and on the size relative to the mean. The idf-like factor changes the ranking only when the query has two or more terms, because it then sets how much each term weighs against the others.
The form of T. With and , . So is the term frequency part of BM25 divided by , with the document frequency of the term in the collection in place of the term frequency, and the collection size in place of the document length.
Cost. Let be the number of query terms, with repeats. Line L3 costs dictionary lookups, and lines L4 to L11 cost arithmetic operations and lookups. Line L12 sorts scores in . So a query costs time with hash table lookups, expected, and extra space. The descriptions take space proportional to the total size of the vocabularies of the collections.
Complexity
Line L3 takes lookups in the descriptions, and lines L4 to L11 take arithmetic operations and lookups. Line L12 sorts scores in ; a heap gives the top in . With hash tables for the descriptions, a query costs expected time on the word RAM, and extra space. The descriptions need one entry for each distinct term of each collection. They are much smaller than the collections, which is the reason to rank collections and not documents at the broker.
Properties
- Bounded. Every score lies in , and a collection with none of the query terms scores exactly .
- Size-aware. For the same , a larger collection gets a smaller . This keeps a huge collection from winning only because it is huge.
- Not a probability of relevance. The beliefs come from an inference network with fitted constants. They rank collections; their values have no direct meaning, and the scores of two queries cannot be compared.
- Deterministic. With the tie rule of line L12, equal descriptions give equal output.
Variants and improvements
- Sampled descriptions. When the engines do not export their statistics, the broker estimates and from documents that it gets back for probe queries. CORI then runs on the estimates. The sampled counts are much smaller than the true counts, so for rare terms is small next to the constants even in large collections, which flattens the scores as in the example.
- Other constants. D'Souza, Zobel and Thom explored other values of the constants on other test data, and in their experiments a plain inner product often did as well as CORI or better. They write the size term as with and , the values fitted on TREC disk 1.
- Other operators. The inference network also allows weighted sums and Boolean operators over the term beliefs, in place of the plain mean.
- Methods that estimate relevant documents. Later selection methods estimate the number of relevant documents in each collection from a central sample index, which helps when the collections differ much in size. See federated search for these methods.
When to use it
Use CORI as a cheap and well-known baseline for resource selection when you have term statistics (or samples) for each collection and the collections are of moderate and similar size. Check it against a plain inner product or a sample-based method on your own queries, since the constants were fitted on one test setting and later studies found that CORI is not always the best choice.
Pitfalls
- The constants are fitted, not derived. The values 50, 150 and 0.4 come from experiments on TREC data split into collections. With very small or very unequal collections, they can be a poor fit.
- Small collections give flat scores. When is much less than 50, is close to 0 and all scores stay near , as in the example. Rankings still follow the formula, but the differences are tiny and easily lost to rounding in later steps.
- The meaning of cw. The papers define as the number of words in the collection. Implementations differ on whether that counts tokens or distinct terms. The two choices give different scores; state which one you use.
- Two meanings of cf. In the CORI papers, cf is the number of collections that contain a term. In most of information retrieval, cf is the number of occurrences of a term. Mixing them up breaks .
- An unknown term. If no collection contains a query term, is undefined. Give the default belief to every collection, or drop the term; both keep the ranking.
- Several published forms. The 1995 paper used another form of , with a logarithm of and a default of 0.4 inside . Name the form you use; this page uses the form of Callan's 2000 chapter.
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/cori-resource-selection/. The authors are listed in prov/47WHK1.jsonl.
"""CORI resource selection (Callan, Lu and Croft 1995; the form of Callan 2000).
A collection is described by df_i(t), the number of its documents that
contain t, and cw_i, its number of tokens. For a query term t and
collection i, with K collections of which c(t) contain t:
T = df / (df + 50 + 150 * cw_i / avg_cw)
I = log((K + 0.5) / c(t)) / log(K + 1.0)
p(t | i) = b + (1 - b) * T * I, b = 0.4
The score of a collection is the mean of p(t | i) over the query terms.
The constants 50, 150 and 0.4 were fitted on test data. A term that no
collection contains gives every collection the default belief b.
The ratio of two logarithms does not depend on their base.
"""
import math
from typing import Iterable, Sequence
DF_BASE = 50.0
DF_SIZE = 150.0
B = 0.4
class Description:
"""The statistics that the broker keeps for one collection."""
def __init__(self, docs: Iterable[Sequence[str]]) -> None:
self.df: dict[str, int] = {}
self.cw = 0
for toks in docs:
self.cw += len(toks) # @line L1
for t in set(toks):
self.df[t] = self.df.get(t, 0) + 1
def cori_scores(query: Sequence[str], descs: Sequence[Description], b: float = B, df_base: float = DF_BASE, df_size: float = DF_SIZE) -> list[float]:
"""The CORI belief of each collection for the query (a bag of terms, repeats count)."""
if not query:
raise ValueError("empty query")
k = len(descs)
if k == 0:
return []
avg_cw = sum(d.cw for d in descs) / k # @line L2
if avg_cw == 0:
raise ValueError("all collections are empty")
c = {t: sum(1 for d in descs if d.df.get(t, 0) > 0) for t in set(query)} # @line L3
scores = []
for d in descs: # @line L4
s = 0.0 # @line L5
for t in query: # @line L6
if c[t] == 0: # @line L7
s += b
continue
df = d.df.get(t, 0)
tt = df / (df + df_base + df_size * d.cw / avg_cw) # @line L8
ii = math.log((k + 0.5) / c[t]) / math.log(k + 1.0) # @line L9
s += b + (1 - b) * tt * ii # @line L10
scores.append(s / len(query)) # @line L11
return scores
def cori_select(query: Sequence[str], descs: Sequence[Description], n: int, b: float = B) -> list[int]:
"""Indexes of the n collections with the highest belief; ties go to the smaller index."""
s = cori_scores(query, descs, b)
return sorted(range(len(descs)), key=lambda i: (-s[i], i))[:n] # @line L12
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_cori_resource_selection.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cori-resource-selection/. The authors are listed in prov/47WHK1.jsonl.
import math
import random
import pytest
import irtoy
from cori_resource_selection import Description, cori_scores, cori_select
# The split of the page: three collections of the irtoy documents.
GROUPS = [[1, 2, 8], [3, 4, 5], [6, 7]]
def toy() -> list[Description]:
return [Description([irtoy.tokenize(irtoy.DOCS[d]) for d in g]) for g in GROUPS]
def direct(query: list[str], groups: list[list[list[str]]]) -> list[float]:
"""CORI written out term by term from the raw documents, with the formula of Callan (2000)."""
k = len(groups)
cw = [sum(len(doc) for doc in g) for g in groups]
avg = sum(cw) / k
out = []
for i, g in enumerate(groups):
total = 0.0
for t in query:
df = sum(1 for doc in g if t in doc)
c = sum(1 for h in groups if any(t in doc for doc in h))
if c == 0:
total += 0.4
continue
big_t = df / (df + 50 + 150 * cw[i] / avg)
big_i = math.log10((k + 0.5) / c) / math.log10(k + 1.0)
total += 0.4 + 0.6 * big_t * big_i
out.append(total / len(query))
return out
def test_toy_example() -> None:
d = toy()
assert [x.cw for x in d] == [29, 30, 20]
q1 = irtoy.tokenize(irtoy.QUERIES["q1"])
s = cori_scores(q1, d)
assert [round(x, 6) for x in s] == [0.403969, 0.400364, 0.40049]
assert cori_select(q1, d, 3) == [0, 2, 1]
assert round(cori_scores(["array"], d)[0], 6) == 0.407455
q2 = irtoy.tokenize(irtoy.QUERIES["q2"])
assert cori_select(q2, d, 1) == [1]
q3 = irtoy.tokenize(irtoy.QUERIES["q3"])
assert cori_select(q3, d, 1) == [2]
def test_term_in_no_collection_gives_default_belief_and_ties() -> None:
d = toy()
q4 = irtoy.tokenize(irtoy.QUERIES["q4"])
assert cori_scores(q4, d) == [0.4, 0.4, 0.4]
assert cori_select(q4, d, 2) == [0, 1]
def test_matches_direct_formula() -> None:
rng = random.Random(8)
words = ["w%d" % j for j in range(12)]
for _ in range(200):
k = rng.randrange(1, 6)
groups = [[[rng.choice(words) for _ in range(rng.randrange(1, 9))] for _ in range(rng.randrange(1, 7))] for _ in range(k)]
query = [rng.choice(words + ["zz"]) for _ in range(rng.randrange(1, 5))]
got = cori_scores(query, [Description(g) for g in groups])
want = direct(query, groups)
assert all(abs(x - y) < 1e-12 for x, y in zip(got, want))
def test_bounds_and_monotonicity() -> None:
rng = random.Random(10)
for _ in range(200):
k = rng.randrange(1, 6)
groups = [[["a"] * rng.randrange(0, 3) + ["b"] * rng.randrange(1, 4) for _ in range(rng.randrange(1, 6))] for _ in range(k)]
d = [Description(g) for g in groups]
for x in cori_scores(["a", "b"], d):
assert 0.4 <= x < 1.0
# More documents with the term, same size: higher belief.
small = Description([["a", "x"], ["x", "x"]])
more = Description([["a", "x"], ["a", "x"]])
other = Description([["y", "y"], ["y", "y"]])
s = cori_scores(["a"], [small, more, other])
assert s[1] > s[0] > s[2] == 0.4
# Same df, larger collection: lower belief.
short = Description([["a"], ["z"]])
long = Description([["a", "z", "z", "z"], ["z", "z", "z", "z"]])
s = cori_scores(["a"], [short, long])
assert s[0] > s[1]
def test_repeated_query_terms_count() -> None:
d = toy()
s1 = cori_scores(["array"], d)
s2 = cori_scores(["array", "array", "rank"], d)
s3 = cori_scores(["rank"], d)
assert all(abs(x - (2 * a + c) / 3) < 1e-15 for x, a, c in zip(s2, s1, s3))
def test_errors() -> None:
with pytest.raises(ValueError):
cori_scores([], toy())
with pytest.raises(ValueError):
cori_scores(["a"], [Description([]), Description([[]])])
assert cori_scores(["a"], []) == []
History
Callan, Lu and Croft presented the method at SIGIR 1995. They built an inference network, as in the INQUERY retrieval system, in which collections take the place of documents. The form of the belief changed over the next years: D'Souza, Zobel and Thom trace an early form with and a default , which was later set to 0, and they report that the constants were fitted on TREC disk 1 split into collections and were not tuned again in later work. Callan's 2000 chapter "Distributed information retrieval" gives the form with 50 and 150 that most later work cites, together with a result merging heuristic. CORI then became the standard baseline of resource selection, and Shokouhi and Si describe it in their 2011 survey of federated search.
References
- Jamie Callan, Distributed information retrieval, in W. Bruce Croft (ed), Advances in Information Retrieval, Kluwer Academic Publishers, 2000, Chapter 5, 127-150, Section 4 (resource selection with the CORI belief, equations 5.1 to 5.4, with b = 0.4) and Section 5 (merging of the result lists); the page uses the formula in this form
- James P. Callan, Zhihong Lu and W. Bruce Croft, Searching distributed collections with inference networks, Proceedings of the 18th Annual International ACM SIGIR Conference (SIGIR 1995), 21-28, the inference network over collections, with collections in place of documents and document frequency in place of term frequency, and the first experiments on TREC data
- Daryl D'Souza, Justin Zobel and James A. Thom, Is CORI effective for collection selection? An exploration of parameters, queries, and data, Proceedings of the 9th Australasian Document Computing Symposium (ADCS 2004), the history of the CORI formula and of its constants (fitted on TREC disk 1 split into collections), and the experiments in which a plain inner product often matched or beat CORI
- Milad Shokouhi and Luo Si, Federated search, Foundations and Trends in Information Retrieval 5(1), 1-102 (2011), the chapter on collection selection, where CORI is one of the methods that treat each collection as one big document
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 47WHK1 Edit this page History Report an error Markdown