Algorithmadvanced
Rank join
Also called HRJN, hash rank join.
Join two inputs sorted by score and output the results in order of a monotone combined score. Stop when a threshold shows that no pair not yet formed can enter the top k.
- Solves
- Top-k query problem
- Time
- O(n + m + n m log(n + m)) worstO(d + (j + k) log(j + 2)) average
- Space
- O(d + j) extra
- Where
- d = the number of tuples read; j = the number of join pairs formed from the tuples read; k = the number of results asked for; m = the number of tuples of R; n = the number of tuples of L
- Model
- Word RAM
- Properties
- deterministicexactnot externalnot in placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ihab F. Ilyas, Walid G. Aref, Ahmed K. Elmagarmid, 2003
A rank join is a join operator that reads two inputs, each sorted by a score from high to low, and outputs the join results in order of a combined score such as the sum. It stops as soon as it has results and a threshold shows that no pair it has not yet formed can score higher. It answers a top-k query whose objects are the results of a join, not objects that occur once in every list. The threshold algorithm solves the case where every list holds the same objects and it needs random access to look up an object in the other lists. The hash rank join (HRJN) uses only sorted access and a hash join on what it has read, like the no-random-access algorithm.
In plain words
Two shops each list their products from the most to the least popular. You want the 2 best pairs of products, one from each shop, that fit together, where the score of a pair is the sum of the two popularity scores.
You read the two lists a little at a time, and you keep every product you read. Each time you read a product, you check it against the products of the other shop that you already read, and you put each pair that fits in a ranked list.
You stop when your best pairs score at least as much as any pair you could still build. A pair that is not built yet needs a product that you have not read. Such a product scores no more than the last product read from its shop, so you can compute the best score that any such pair can have.
The problem
The input is two lists and of and tuples. Each tuple has a join key and a score, and each list is sorted by score from high to low. The join condition is equality of keys, and a NULL key never matches. The score of a join result is , where is monotone: whenever and . Sum, weighted sum, minimum, maximum and the product of scores that are not negative are monotone. The output is join results with the largest scores, in order of score, with ties broken in any way, under bag semantics.
Cost model. The main measure is the depth: the number of tuples read from each input, and , with . In a pipelined plan each read pulls a tuple from a child operator, so the depth is the work that the operator causes below it. The second measure is the work in the word RAM, with hash tables and a binary heap.
The algorithm
HRJN(L, R, f, k) ▷ L and R sorted by score, highest first- 1
H_L, H_R ← empty hash tables on the join key; Q ← an empty max-priority queue on the score - 2
if L or R is empty or k = 0 then return the empty list - 3
while fewer than k results are output and L or R is not exhausted do - 4
choose an input I that is not exhausted ▷ in turn, or by the HRJN* rule - 5
t ← the next tuple of I; bottom_I ← score(t); insert t in H_I - 6
for each tuple u of the other table with the key of t do insert the pair of t and u in Q - 7
T ← the largest of f(top_L, bottom_R) if R is not exhausted and f(bottom_L, top_R) if L is not exhausted; T ← −∞ if both are exhausted - 8
while Q is not empty, the top score of Q is at least T and fewer than k results are output do output the top of Q - 9
while Q is not empty and fewer than k results are output do output the top of Q - 10
return the output
Here is the score of the first tuple of and is the score of the last tuple read from . Before the first read from an input, the implementation uses as the threshold. An input is exhausted when all its tuples have been read, and then its term leaves the threshold, because no pair can use an unread tuple of it.
The threshold is the corner bound. A pair that is not formed has a tuple of that is not read, or a tuple of that is not read. In the first case and the other score is at most , so the pair scores at most . The second case is symmetric.
Which input to read (line L4). HRJN reads the inputs in turn. HRJN* reads when , and otherwise, because only a read from can lower the first term. The choice changes the depth, not the result.
Example
Let be the sum, , and , each written as (key, score). HRJN reads the inputs in turn.
| read | tuple | new pairs in Q | threshold T | output |
|---|---|---|---|---|
| 1 | : | |||
| 2 | : | |||
| 3 | : | : 17 | ||
| 4 | : | : 17 | both pairs with 17 |
The operator stops after 4 of the 9 tuples. For it continues. The third pair with score 11 is formed at read 6, but the threshold falls only to 16, 16 and then 12 at read 8, when is exhausted and . The bound assumes that the next tuple of has score 3 and joins with . Only read 9 exhausts and lets the operator output 11. So a loose corner bound can force the operator to read all the input.
The pull rule. Ilyas et al. compare the two rules on the scores and with the sum. After 3 reads from each input, . HRJN* reads twice and four times in the same 6 reads, and gets . A lower threshold lets the operator output its results sooner.
Correctness
Each pair of the join is put in the queue exactly once, when the later of its two tuples is read, because the earlier tuple is then in its hash table. A pair that is not yet formed has an unread tuple, so by monotonicity it scores at most . When line L8 outputs a pair, its score is at least and at least every score in the queue, so no pair that is not output yet has a higher score. The outputs therefore come in order of score, and the first of them are a top-k answer. The full proof is in the proof page.
The proof needs to be monotone. If is not monotone, a tuple with a low score can still give a high combined score, and no bound from the scores read so far is safe.
Proof: The hash rank join outputs the join in non-increasing order of a monotone score, so its first k results are a top-k answerfull
We use the line numbers of the pseudocode. has tuples and has tuples, each sorted by score from high to low. We treat each stored tuple as a distinct occurrence, so the join is a bag of pairs with equal keys that are not NULL, and the score of a pair is , also written for a pair . The function is monotone: when and . We write for the score of the first tuple of and for the score of the last tuple read from , and the same for . An input is exhausted when all its tuples have been read.
Lemma 1 (each pair is formed once). A pair enters the queue exactly once, at the read of whichever of and is read later, and never before.
Proof. Say is read after . When is read (line L5), is already in the table of , under its key, because line L5 inserts every tuple with a key that is not NULL when it is read. So line L6 finds among the tuples of the table of with the key of and inserts in the queue. At the earlier read of , was not in the table of , so that read did not form the pair. A tuple is read only once, so no other read forms it. A tuple with a NULL key is not inserted and does not probe, which matches the join. The case where is read later is the same.
So at any time each pair of is in exactly one of three states: output, queued or unformed, and a pair is unformed exactly when at least one of its tuples is not yet read.
Lemma 2 (threshold). After line L7, every unformed pair has score at most .
Proof. Take an unformed pair . Suppose first that is not read. Then is not exhausted, and since is sorted, if some tuple of has been read, and in any case. Also . If both inputs have been read at least once, the term is part of , and monotonicity gives . If one input has not been read at all, the term is part of , and . The case where is not read is symmetric, with the term . If both inputs are exhausted, no pair is unformed and is correct.
Lemma 3 (output step). When a pair is output, at line L8 or line L9, every pair of that is not yet output has score at most .
Proof. Pairs that are queued have score at most , because is the maximum of the queue. At line L8, , so by Lemma 2 every unformed pair has score at most . At line L9 both inputs are exhausted, so no pair is unformed.
Theorem 1 (correctness). Let be the output. Then each pair of appears at most once, , and for each the pairs have the largest scores of : no pair of outside them has a larger score than . The output has pairs, and with unbounded it is all of .
Proof. A pair is output only after it is queued, it is removed from the queue when it is output, and by Lemma 1 it is queued once, so it is output at most once. Lemma 3 at the output of says that every pair not among , and in particular , has score at most . This gives both the order and the top- property. For the count: the loop of line L3 ends when pairs are output or both inputs are exhausted. In the second case every pair of is formed by Lemma 1, so line L9 outputs from the queue until pairs are output or the queue is empty, that is, until pairs are output.
The proof uses only that is monotone. For a function that is not monotone, an unread tuple with a low score can still give a high combined score, Lemma 2 fails, and no threshold that uses only the scores read so far is safe.
Theorem 2 (termination and cost). The algorithm stops after at most iterations of the loop of line L3. Let and be the number of tuples read from each input when it stops, and let be the number of pairs in the join of these two prefixes. With hash tables in expected time per operation and a binary heap for the queue, the expected work is and the space is .
Proof. Each iteration reads one new tuple at line L5, so there are at most iterations, and line L9 pops at most pairs. Each read costs one insertion and one lookup. Line L6 forms each of the pairs once (Lemma 1) and pushes it in time. Line L7 costs evaluations of . Each output is one pop, and at most pops happen. The tables hold the tuples read and the queue holds at most pairs.
The depths and depend on the data. If the tuples with high scores do not join, the algorithm can read both inputs to the end for : take with scores and keys , and with scores and keys and a last tuple with key . The only pair is formed at the last read of , so .
Complexity
- Work. Each read costs one insert and one probe of a hash table, in expected time. Each formed pair costs one push into a binary heap, , and each output costs one pop. The total is expected , where is the number of pairs formed (a theorem in the word RAM). In the worst case and .
- Space. The operator keeps every tuple read and every pair formed but not output: . This is the main practical cost, because nothing read can be dropped while a later tuple of the other input might join with it.
- Depth. The depth depends on the data. When the tuples with high scores join, the depth is small: for two inputs of 200 tuples with scores and keys , so that tuples of equal rank join, reads 5 tuples from each input. When they do not join, the operator can read both inputs to the end even for . Neither rule for line L4 is optimal on every instance.
Properties
- Pipelined. The operator outputs each result as soon as it is safe, so a parent operator, such as another rank join, can pull results one at a time.
- Sorted access only. It never looks up a key in an input that it has not read, unlike the threshold algorithm.
- Bag semantics. Each pair of tuples with equal keys is a separate result, so duplicates in the inputs give duplicate results.
- Ties. Results with equal scores come in the order in which they were formed. The order of the scores does not depend on the pull rule, but which of several tied pairs is output first can.
Variants and improvements
- Multiway rank join. A plan for several inputs is a tree of binary rank joins. The output of a child rank join is sorted by its combined score, so it can be the input of the parent, with the score of a partial result as its score.
- Rank join in the optimizer. Ilyas, Shah, Aref, Vitter and Elmagarmid (2004) estimate the depth of each input, so that the query optimizer can compare a plan with rank joins against a plan that joins everything and then sorts.
- Tighter bounds. Schnaitter and Polyzotis (2008) showed that the corner bound can be far from the best possible bound, and gave a tighter bound computed from the tuples already read, with an analysis of the cost of reading.
- Nested-loops rank join. When one input is small or has an index on the key, a rank join can scan the other input in order and look up matches, at the cost of random access.
- The top-k aggregation case. When both lists hold the same objects and the key is the object, a rank join solves the top-k aggregation problem for two lists with sorted access only, as the no-random-access algorithm does.
When to use it
Use a rank join when a query asks for the best results of a join under a monotone score, the inputs can be read in order of score (from an index or from a ranked child operator), and is small compared with the size of the join. The early stop pays off when the high scores of the two inputs tend to join. When the join result is small, a plain hash join followed by a sort or a heap of size is simpler and reads the same input.
Pitfalls
- A score that is not monotone. For example, breaks the threshold, and the operator returns wrong results without any error.
- Threshold terms of exhausted inputs. If a term of an exhausted input stays in , the operator cannot output its last results until both inputs end. If the term of an input that is not exhausted is dropped, results come out too early.
- Unsorted input. An input that is not sorted by score breaks the bound . The implementation checks the order.
- Memory. In the worst case the operator keeps both inputs in memory, like a symmetric hash join.
- NULL keys. A tuple with a NULL key must not be put in a hash table under a NULL entry, because NULL never equals NULL in a join.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the databases pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Naive relations, operators by definition, SQL three-valued logic and a page-counting disk.
This is the reference that the tests of the databases pages compare against.
Every operator here follows its definition directly, with nested loops and no
index, hash table or sort of the input. Do not use it as a fast engine.
Relations
Relation(schema, rows, mode) holds a tuple of distinct attribute names and
a collections.Counter from tuples to positive counts. mode is "bag" (the
default, SQL semantics) or "set" (relational theory); in set mode every
count is 1. rows may be an iterable of tuples (duplicates add up) or a
mapping from tuples to counts. Two relations are equal when they have the
same attributes (in any column order) and the same count for each tuple.
The mode is not compared.
Operators (each returns a new Relation in the mode of its input)
select(rel, pred) keeps a row only when pred(row) is True
where(rel, pred) the same as select (the SQL WHERE filter)
project(rel, attrs) bag: counts add up; set: duplicates removed
rename(rel, mapping) mapping is {old: new}
union(r, s) bag: UNION ALL (counts add); set: union
difference(r, s) bag: monus max(0, m - n); set: r - s
intersection(r, s) bag: min(m, n); set: intersection
product(r, s) attributes must be disjoint; counts multiply
natural_join(r, s) nested loops on the common attributes
theta_join(r, s, pred) select(product(r, s), pred)
semijoin(r, s), antijoin(r, s)
distinct(rel) every count becomes 1
aggregate(rel, group_attrs, aggs)
aggs is a list of (func, attr, out) with func in
count_star, count, count_distinct, sum, avg, min, max
A predicate receives the row as a dict from attribute name to value. It may
return True, False or None (UNKNOWN). Only True keeps the row.
Nulls
NULL is None. Joins follow SQL: a common attribute that is None in either
row never matches. aggregate follows SQL: GROUP BY puts all nulls of a
column in one group, every aggregate except count_star skips nulls, and
sum, avg, min and max of no non-null value give None while count gives 0.
With no grouping attributes, aggregate returns one row even for an empty
input, as SQL does.
Expressions
evaluate(expr, db, mode) evaluates a tree of nested tuples:
("scan", name)
("select", pred, e) ("project", attrs, e)
("rename", mapping, e) ("distinct", e)
("union", e1, e2) ("difference", e1, e2)
("intersection", e1, e2) ("product", e1, e2)
("join", e1, e2) ("theta_join", pred, e1, e2)
("semijoin", e1, e2) ("antijoin", e1, e2)
("aggregate", group_attrs, aggs, e)
db maps a name to a Relation. Each scanned relation is first put in mode.
Three-valued logic
tv_and, tv_or and tv_not are the strong Kleene connectives on True, False
and None. cmp3(op, x, y) compares with op in =, <>, !=, <, <=, >, >= and
returns None when x or y is None.
Disk
Disk counts page reads and writes. load(rows, per_page) puts an existing
input on the disk without counting it. paginate(rows, per_page) splits a
list of rows into pages.
Random data
random_relation(rng, schema, n, domain, mode, null_rate) draws n rows.
"""
from collections import Counter
from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence
from fractions import Fraction
from numbers import Number
import random
BAG = "bag"
SET = "set"
MODES = (BAG, SET)
# ---------------------------------------------------------------- ordering
def value_key(v: object) -> tuple:
"""A total order on the values of one column: None first, then numbers, then strings."""
if v is None:
return (0, 0)
if isinstance(v, Number):
return (1, v)
if isinstance(v, str):
return (2, v)
if isinstance(v, tuple):
return (3, tuple(value_key(x) for x in v))
return (4, repr(v))
def row_key(t: Sequence) -> tuple:
"""A total order on tuples that tolerates None. Use it to sort rows in tests."""
return tuple(value_key(v) for v in t)
# ---------------------------------------------------------------- relations
class Relation:
"""A relation: a schema (tuple of names), a Counter of tuples and a mode."""
__slots__ = ("schema", "rows", "mode")
def __init__(self, schema: Sequence[str], rows: Iterable | Mapping = (), mode: str = BAG) -> None:
if mode not in MODES:
raise ValueError("mode must be 'bag' or 'set'")
schema = tuple(schema)
if len(set(schema)) != len(schema):
raise ValueError("duplicate attribute in schema %r" % (schema,))
counts: Counter = Counter()
items = rows.items() if isinstance(rows, Mapping) else ((t, 1) for t in rows)
for t, c in items:
t = tuple(t)
if len(t) != len(schema):
raise ValueError("tuple %r does not fit schema %r" % (t, schema))
if c < 0:
raise ValueError("negative count for %r" % (t,))
if c:
counts[t] += c
if mode == SET:
counts = Counter({t: 1 for t in counts})
self.schema = schema
self.rows = counts
self.mode = mode
def index(self, attr: str) -> int:
return self.schema.index(attr)
def reorder(self, schema: Sequence[str]) -> "Relation":
"""The same relation with its columns in the order of schema."""
schema = tuple(schema)
if sorted(schema) != sorted(self.schema):
raise ValueError("schemas %r and %r differ" % (self.schema, schema))
pos = [self.schema.index(a) for a in schema]
return Relation(schema, {tuple(t[i] for i in pos): c for t, c in self.rows.items()}, self.mode)
def with_mode(self, mode: str) -> "Relation":
return Relation(self.schema, self.rows, mode)
def as_dict(self, t: Sequence) -> dict:
return dict(zip(self.schema, t))
def sorted_rows(self) -> list:
"""Every tuple, repeated by its count, in row_key order."""
out = []
for t in sorted(self.rows, key=row_key):
out.extend([t] * self.rows[t])
return out
def __iter__(self):
return iter(self.sorted_rows())
def __len__(self) -> int:
return sum(self.rows.values())
def __eq__(self, other: object) -> bool:
if not isinstance(other, Relation):
return NotImplemented
if sorted(self.schema) != sorted(other.schema):
return False
return self.rows == other.reorder(self.schema).rows
def __repr__(self) -> str:
body = ", ".join("%r: %d" % (t, self.rows[t]) for t in sorted(self.rows, key=row_key))
return "Relation(%r, {%s}, %r)" % (self.schema, body, self.mode)
def _mode2(r: Relation, s: Relation) -> str:
if r.mode != s.mode:
raise ValueError("operands have modes %r and %r" % (r.mode, s.mode))
return r.mode
def _same_schema(r: Relation, s: Relation) -> Relation:
"""s with its columns in the order of r; the attribute sets must be equal."""
if sorted(r.schema) != sorted(s.schema):
raise ValueError("union-incompatible schemas %r and %r" % (r.schema, s.schema))
return s.reorder(r.schema)
# ---------------------------------------------------------------- three-valued logic
def tv_and(a: bool | None, b: bool | None) -> bool | None:
if a is False or b is False:
return False
if a is None or b is None:
return None
return True
def tv_or(a: bool | None, b: bool | None) -> bool | None:
if a is True or b is True:
return True
if a is None or b is None:
return None
return False
def tv_not(a: bool | None) -> bool | None:
return None if a is None else not a
_CMP = {
"=": lambda x, y: x == y,
"<>": lambda x, y: x != y,
"!=": lambda x, y: x != y,
"<": lambda x, y: x < y,
"<=": lambda x, y: x <= y,
">": lambda x, y: x > y,
">=": lambda x, y: x >= y,
}
def cmp3(op: str, x: object, y: object) -> bool | None:
"""SQL comparison: None (UNKNOWN) if either side is NULL."""
if op not in _CMP:
raise ValueError("unknown comparison %r" % (op,))
if x is None or y is None:
return None
return bool(_CMP[op](x, y))
def is_true(v: bool | None) -> bool:
"""The WHERE test: only True passes; False and None (UNKNOWN) do not."""
return v is True
# ---------------------------------------------------------------- operators
def select(rel: Relation, pred: Callable[[dict], bool | None]) -> Relation:
out = {t: c for t, c in rel.rows.items() if pred(rel.as_dict(t)) is True}
return Relation(rel.schema, out, rel.mode)
where = select
def project(rel: Relation, attrs: Sequence[str]) -> Relation:
attrs = tuple(attrs)
pos = [rel.index(a) for a in attrs]
out: Counter = Counter()
for t, c in rel.rows.items():
out[tuple(t[i] for i in pos)] += c
return Relation(attrs, out, rel.mode)
def rename(rel: Relation, mapping: Mapping[str, str]) -> Relation:
for a in mapping:
if a not in rel.schema:
raise ValueError("no attribute %r to rename" % (a,))
return Relation(tuple(mapping.get(a, a) for a in rel.schema), rel.rows, rel.mode)
def union(r: Relation, s: Relation) -> Relation:
mode = _mode2(r, s)
s = _same_schema(r, s)
out = Counter(r.rows)
out.update(s.rows)
return Relation(r.schema, out, mode)
def difference(r: Relation, s: Relation) -> Relation:
mode = _mode2(r, s)
s = _same_schema(r, s)
out = {t: max(0, c - s.rows.get(t, 0)) for t, c in r.rows.items()}
return Relation(r.schema, out, mode)
def intersection(r: Relation, s: Relation) -> Relation:
mode = _mode2(r, s)
s = _same_schema(r, s)
out = {t: min(c, s.rows.get(t, 0)) for t, c in r.rows.items()}
return Relation(r.schema, out, mode)
def product(r: Relation, s: Relation) -> Relation:
mode = _mode2(r, s)
common = [a for a in r.schema if a in s.schema]
if common:
raise ValueError("product needs disjoint schemas; common: %r" % (common,))
out: Counter = Counter()
for t, c in r.rows.items():
for u, d in s.rows.items():
out[t + u] += c * d
return Relation(r.schema + s.schema, out, mode)
def _matches(r: Relation, s: Relation, t: tuple, u: tuple, common: Sequence[str]) -> bool:
for a in common:
x, y = t[r.index(a)], u[s.index(a)]
if x is None or y is None or x != y:
return False
return True
def natural_join(r: Relation, s: Relation) -> Relation:
"""Nested loops over both inputs. With no common attribute it is the product."""
mode = _mode2(r, s)
common = [a for a in r.schema if a in s.schema]
rest = [a for a in s.schema if a not in common]
rest_pos = [s.index(a) for a in rest]
out: Counter = Counter()
for t, c in r.rows.items():
for u, d in s.rows.items():
if _matches(r, s, t, u, common):
out[t + tuple(u[i] for i in rest_pos)] += c * d
return Relation(r.schema + tuple(rest), out, mode)
def theta_join(r: Relation, s: Relation, pred: Callable[[dict], bool | None]) -> Relation:
return select(product(r, s), pred)
def semijoin(r: Relation, s: Relation) -> Relation:
"""Rows of r (with their counts) that join with at least one row of s."""
_mode2(r, s)
common = [a for a in r.schema if a in s.schema]
out = {t: c for t, c in r.rows.items() if any(_matches(r, s, t, u, common) for u in s.rows)}
return Relation(r.schema, out, r.mode)
def antijoin(r: Relation, s: Relation) -> Relation:
"""Rows of r (with their counts) that join with no row of s."""
_mode2(r, s)
common = [a for a in r.schema if a in s.schema]
out = {t: c for t, c in r.rows.items() if not any(_matches(r, s, t, u, common) for u in s.rows)}
return Relation(r.schema, out, r.mode)
def distinct(rel: Relation) -> Relation:
return Relation(rel.schema, {t: 1 for t in rel.rows}, rel.mode)
AGG_FUNCS = ("count_star", "count", "count_distinct", "sum", "avg", "min", "max")
def _avg(vals: list) -> object:
total = sum(vals)
if all(isinstance(v, (int, Fraction)) for v in vals):
return Fraction(total, 1) / len(vals)
return total / len(vals)
def agg_value(func: str, vals: list) -> object:
"""One SQL aggregate over a list of column values (with repeats). count_star counts all."""
if func == "count_star":
return len(vals)
nn = [v for v in vals if v is not None]
if func == "count":
return len(nn)
if func == "count_distinct":
seen: list = []
for v in nn:
if v not in seen:
seen.append(v)
return len(seen)
if not nn:
return None
if func == "sum":
return sum(nn)
if func == "avg":
return _avg(nn)
if func == "min":
return min(nn)
if func == "max":
return max(nn)
raise ValueError("unknown aggregate %r" % (func,))
def aggregate(rel: Relation, group_attrs: Sequence[str], aggs: Sequence[tuple]) -> Relation:
"""gamma_{G; f(A) -> B}(rel) by definition.
aggs is a list of (func, attr, out); attr is ignored for count_star and may
be None. For each distinct group key, in row_key order, the whole input is
scanned. Each result row has count 1 in either mode.
"""
group_attrs = tuple(group_attrs)
gpos = [rel.index(a) for a in group_attrs]
for func, attr, _ in aggs:
if func not in AGG_FUNCS:
raise ValueError("unknown aggregate %r" % (func,))
if func != "count_star":
rel.index(attr)
keys: list = []
for t in rel.rows:
k = tuple(t[i] for i in gpos)
if k not in keys:
keys.append(k)
if not group_attrs and not keys:
keys = [()]
out: Counter = Counter()
for k in sorted(keys, key=row_key):
row = list(k)
for func, attr, _ in aggs:
vals: list = []
for t, c in rel.rows.items():
if tuple(t[i] for i in gpos) == k:
vals.extend([None if func == "count_star" else t[rel.index(attr)]] * c)
row.append(agg_value(func, vals))
out[tuple(row)] = 1
schema = group_attrs + tuple(o for _, _, o in aggs)
return Relation(schema, out, rel.mode)
# ---------------------------------------------------------------- evaluation
def evaluate(expr: tuple, db: Mapping[str, Relation], mode: str = BAG) -> Relation:
"""Evaluate an expression tree of nested tuples over db, in mode."""
if mode not in MODES:
raise ValueError("mode must be 'bag' or 'set'")
op = expr[0]
ev = lambda e: evaluate(e, db, mode)
if op == "scan":
return db[expr[1]].with_mode(mode)
if op == "select":
return select(ev(expr[2]), expr[1])
if op == "project":
return project(ev(expr[2]), expr[1])
if op == "rename":
return rename(ev(expr[2]), expr[1])
if op == "distinct":
return distinct(ev(expr[1]))
if op == "aggregate":
return aggregate(ev(expr[3]), expr[1], expr[2])
if op == "theta_join":
return theta_join(ev(expr[2]), ev(expr[3]), expr[1])
binary = {
"union": union, "difference": difference, "intersection": intersection,
"product": product, "join": natural_join, "semijoin": semijoin, "antijoin": antijoin,
}
if op in binary:
return binary[op](ev(expr[1]), ev(expr[2]))
raise ValueError("unknown operator %r" % (op,))
# ---------------------------------------------------------------- disk
def paginate(rows: Sequence, per_page: int) -> list:
"""Split rows into pages of per_page rows; the last page may be shorter."""
if per_page < 1:
raise ValueError("per_page must be at least 1")
rows = list(rows)
return [rows[i:i + per_page] for i in range(0, len(rows), per_page)]
class Disk:
"""Pages on a simulated disk. Each read_page and write_page call costs one I/O."""
def __init__(self) -> None:
self.pages: dict = {}
self.reads = 0
self.writes = 0
self._next = 0
def alloc(self) -> int:
pid = self._next
self._next += 1
self.pages[pid] = ()
return pid
def write_page(self, pid: int, rows: Iterable) -> None:
if pid not in self.pages:
raise KeyError("page %r was not allocated" % (pid,))
self.pages[pid] = tuple(rows)
self.writes += 1
def read_page(self, pid: int) -> list:
self.reads += 1
return list(self.pages[pid])
def free(self, pid: int) -> None:
del self.pages[pid]
def load(self, rows: Sequence, per_page: int) -> list:
"""Store an input file without counting I/O; return its page ids in order."""
ids = []
for page in paginate(rows, per_page):
pid = self.alloc()
self.pages[pid] = tuple(page)
ids.append(pid)
return ids
def io(self) -> int:
return self.reads + self.writes
def reset_counters(self) -> None:
self.reads = 0
self.writes = 0
# ---------------------------------------------------------------- random data
def random_relation(rng: random.Random, schema: Sequence[str], n: int,
domain: int | Sequence | Mapping = 4, mode: str = BAG,
null_rate: float = 0.0) -> Relation:
"""n rows drawn with rng. domain is a size k (values 0 to k - 1), a list of
values, or a dict from attribute to either. Each value is None with
probability null_rate. In set mode duplicates collapse, so there may be
fewer than n rows."""
schema = tuple(schema)
def values(a: str) -> list:
d = domain[a] if isinstance(domain, Mapping) else domain
return list(range(d)) if isinstance(d, int) else list(d)
doms = [values(a) for a in schema]
rows = []
for _ in range(n):
t = []
for d in doms:
if null_rate and rng.random() < null_rate:
t.append(None)
else:
t.append(rng.choice(d))
rows.append(tuple(t))
return Relation(schema, rows, mode)
rank_join.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rank-join/. The authors are listed in prov/TEN8RX.jsonl.
"""Hash rank join (HRJN) of two inputs sorted by score, with the HRJN* pull rule.
Each input is a list of tuples sorted by the score column, highest first. The
join condition is equality of the key columns, and a NULL key (None) never
matches. The score of a join result is f(score of the left tuple, score of the
right tuple), where f must be monotone: f(x, y) <= f(x2, y2) when x <= x2 and
y <= y2. The default f is the sum.
rank_join returns the join results in non-increasing order of score and stops
after k of them (k=None gives the whole join). The threshold after each read
is the largest score that a combination not yet formed can have:
T = max(f(top_L, bottom_R), f(bottom_L, top_R)),
where top is the first score of an input and bottom the last score read. A
term is left out when its input is exhausted, and T is minus infinity when
both are. A result in the queue is output once its score is at least T.
"""
import heapq
import itertools
import operator
from collections.abc import Callable, Sequence
NEG_INF = float("-inf")
def _check_sorted(rows: Sequence[tuple], col: int, name: str) -> None:
for a, b in zip(rows, rows[1:]):
if a[col] < b[col]:
raise ValueError(f"input {name} is not sorted by score, highest first")
def rank_join(left: Sequence[tuple], right: Sequence[tuple], k: int | None = None,
f: Callable = operator.add, strategy: str = "alternate",
lkey: int = 0, lscore: int = 1, rkey: int = 0, rscore: int = 1):
"""Top-k equi-join of left and right by f(score_l, score_r).
strategy is "alternate" (read the inputs in turn) or "adaptive" (HRJN*:
read the input whose term of the threshold is larger). Returns (out, stats)
where out is a list of (score, l, r) and stats has the depths (tuples read
from each input), the threshold after each read and the largest queue size.
"""
if strategy not in ("alternate", "adaptive"):
raise ValueError("strategy must be 'alternate' or 'adaptive'")
_check_sorted(left, lscore, "left")
_check_sorted(right, rscore, "right")
inputs = (left, right)
keys = (lkey, rkey)
scores = (lscore, rscore)
tables = ({}, {}) # @line L1
queue: list = []
tie = itertools.count()
out: list = []
stats = {"depth": [0, 0], "thresholds": [], "max_queue": 0}
limit = float("inf") if k is None else k
if not left or not right or limit <= 0: # @line L2
return out, stats
depth = stats["depth"]
top = (left[0][lscore], right[0][rscore])
bottom = [top[0], top[1]]
turn = 0
def exhausted(i: int) -> bool:
return depth[i] == len(inputs[i])
while len(out) < limit and not (exhausted(0) and exhausted(1)): # @line L3
if depth[0] == 0 or depth[1] == 0:
i = 0 if depth[0] == 0 else 1
elif strategy == "alternate":
i = turn
else:
i = 1 if f(top[0], bottom[1]) > f(bottom[0], top[1]) else 0
if exhausted(i):
i = 1 - i # @line L4
t = inputs[i][depth[i]]
depth[i] += 1
bottom[i] = t[scores[i]] # @line L5
turn = 1 - i
key = t[keys[i]]
if key is not None:
tables[i].setdefault(key, []).append(t)
for u in tables[1 - i].get(key, ()): # @line L6
l, r = (t, u) if i == 0 else (u, t)
s = f(l[lscore], r[rscore])
heapq.heappush(queue, (-s, next(tie), l, r))
stats["max_queue"] = max(stats["max_queue"], len(queue))
terms = []
if not exhausted(1) and depth[1] > 0:
terms.append(f(top[0], bottom[1]))
if not exhausted(0) and depth[0] > 0:
terms.append(f(bottom[0], top[1]))
if depth[0] == 0 or depth[1] == 0:
terms.append(f(top[0], top[1]))
threshold = max(terms) if terms else NEG_INF # @line L7
stats["thresholds"].append(threshold)
while queue and -queue[0][0] >= threshold and len(out) < limit: # @line L8
s, _, l, r = heapq.heappop(queue)
out.append((-s, l, r))
while queue and len(out) < limit: # @line L9
s, _, l, r = heapq.heappop(queue)
out.append((-s, l, r))
return out, stats # @line L10
test_rank_join.py 95 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rank-join/. The authors are listed in prov/TEN8RX.jsonl.
import operator
import random
from collections import Counter
import pytest
from dbrel import Relation, evaluate
from rank_join import rank_join
FUNCS = (operator.add, lambda x, y: 2 * x + y, min, max, lambda x, y: x * y)
def oracle(left, right):
"""The bag join by dbrel, as a Counter of (key, score_l, id_l, score_r, id_r)."""
db = {"L": Relation(("k", "sl", "il"), left), "R": Relation(("k", "sr", "ir"), right)}
res = evaluate(("join", ("scan", "L"), ("scan", "R")), db).reorder(("k", "sl", "il", "sr", "ir"))
return Counter(res.rows)
def flat(out):
return Counter((l[0], l[1], l[2], r[1], r[2]) for _, l, r in out)
def test_example() -> None:
left = [("a", 10, 0), ("b", 8, 1), ("c", 5, 2), ("a", 3, 3), ("b", 1, 4)]
right = [("b", 9, 0), ("a", 7, 1), ("c", 6, 2), ("b", 2, 3)]
out, stats = rank_join(left, right, 2)
assert [s for s, _, _ in out] == [17, 17] and stats["depth"] == [2, 2]
assert stats["thresholds"] == [19, 19, 19, 17]
out, stats = rank_join(left, right, 3)
assert [s for s, _, _ in out] == [17, 17, 11] and stats["depth"] == [5, 4]
assert stats["thresholds"] == [19, 19, 19, 17, 17, 16, 16, 12, float("-inf")]
def test_paper_thresholds() -> None:
# Scores of Ilyas et al.: reading 3 + 3 gives T = 108, the HRJN* rule
# reads 2 + 4 and gives T = 105. No keys match, so nothing is output.
left = [(f"l{i}", s, i) for i, s in enumerate([100, 50, 25, 10, 1])]
right = [(f"r{i}", s, i) for i, s in enumerate([10, 9, 8, 5, 1])]
_, alt = rank_join(left, right, None, strategy="alternate")
_, ada = rank_join(left, right, None, strategy="adaptive")
assert alt["thresholds"][5] == 108 and ada["thresholds"][5] == 105
assert alt["thresholds"][:6] == [110, 110, 110, 109, 109, 108]
assert ada["thresholds"][:6] == [110, 110, 110, 109, 108, 105]
def test_random_against_oracle() -> None:
rng = random.Random(11)
for trial in range(150):
dom = rng.choice([3, 4, 5])
keys = list(range(dom)) + [None]
left = sorted(((rng.choice(keys), rng.randrange(10), i) for i in range(rng.randrange(0, 25))),
key=lambda t: -t[1])
right = sorted(((rng.choice(keys), rng.randrange(10), i) for i in range(rng.randrange(0, 25))),
key=lambda t: -t[1])
f = FUNCS[trial % len(FUNCS)]
want = oracle(left, right)
ranked = sorted((f(sl, sr) for (_, sl, _, sr, _), c in want.items() for _ in range(c)), reverse=True)
for strategy in ("alternate", "adaptive"):
full, _ = rank_join(left, right, None, f, strategy)
assert flat(full) == want
assert [s for s, _, _ in full] == ranked
for k in (1, 2, 5):
out, stats = rank_join(left, right, k, f, strategy)
assert [s for s, _, _ in out] == ranked[:k]
assert not flat(out) - want
assert all(s == f(l[1], r[1]) for s, l, r in out)
assert stats["depth"][0] <= len(left) and stats["depth"][1] <= len(right)
def test_edges() -> None:
assert rank_join([], [("a", 1, 0)], 3)[0] == []
assert rank_join([("a", 1, 0)], [], 3)[0] == []
assert rank_join([("a", 1, 0)], [("a", 2, 0)], 0)[0] == []
out, _ = rank_join([("a", 1, 0)], [("a", 2, 0)], 5)
assert out == [(3, ("a", 1, 0), ("a", 2, 0))]
same_l = [("x", 5 - i, i) for i in range(4)]
same_r = [("x", 5 - i, i) for i in range(3)]
out, _ = rank_join(same_l, same_r, None)
assert len(out) == 12 and out[0][0] == 10
assert rank_join([(None, 3, 0)], [(None, 3, 0)], None)[0] == []
with pytest.raises(ValueError):
rank_join([("a", 1, 0), ("a", 2, 1)], [("a", 1, 0)], 1)
def test_early_stop_on_correlated_input() -> None:
# When high scores join, the operator reads only a prefix of each input.
left = [(i % 4, 200 - i, i) for i in range(200)]
right = [(i % 4, 200 - i, i) for i in range(200)]
out, stats = rank_join(left, right, 3)
assert [s for s, _, _ in out] == [400, 398, 396]
assert max(stats["depth"]) <= 10
History
Ilyas, Aref and Elmagarmid presented the hash rank join operator HRJN at VLDB 2003, as a physical operator that a relational engine can place in a query plan, and the journal version of 2004 described the adaptive pull rule HRJN*. Ilyas, Shah, Aref, Vitter and Elmagarmid (SIGMOD 2004) added rank joins to a cost-based optimizer with an estimate of the depth. Their work built on the top-k algorithms of Fagin, Lotem and Naor for lists of the same objects, which use sorted and random access. Schnaitter and Polyzotis (2008) studied the cost of rank join algorithms and showed that the corner bound is not tight in general. Ilyas, Beskales and Soliman (2008) surveyed rank join among the top-k techniques in relational systems.
References
- Ihab F. Ilyas, Walid G. Aref and Ahmed K. Elmagarmid, Supporting top-k join queries in relational databases, The VLDB Journal 13(3), 2004, pages 207 to 221, Section 4 (the HRJN operator, its threshold, Theorem 4.2.1 on correctness and the adaptive pulling strategy HRJN*)
- Supporting top-k join queries in relational databases, the conference version of the HRJN operator
- Ihab F. Ilyas, Rahul Shah, Walid G. Aref, Jeffrey S. Vitter and Ahmed K. Elmagarmid, Rank-aware query optimization, SIGMOD 2004, pages 203 to 214, the estimate of the input depth of a rank join and its use in plan enumeration
- Ihab F. Ilyas, George Beskales and Mohamed A. Soliman, A survey of top-k query processing techniques in relational database systems, ACM Computing Surveys 40(4), Article 11, 2008, the sections on rank join and on top-k over sorted lists
- Ronald Fagin, Amnon Lotem and Moni Naor, Optimal aggregation algorithms for middleware, Journal of Computer and System Sciences 66(4), 2003, pages 614 to 656, the threshold algorithm TA, which uses random access, and NRA, which uses sorted access only
- Karl Schnaitter and Neoklis Polyzotis, Evaluating rank joins with optimal cost, PODS 2008, pages 43 to 52, the analysis of the HRJN threshold and a tighter bound for rank join
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 TEN8RX Edit this page History Report an error Markdown