Algorithmadvanced
Ripple join
Also called Haas-Hellerstein ripple join.
A join for online aggregation. It reads both inputs in random order, joins each new tuple with all tuples read from the other input, and scales the running sum into an unbiased estimate.
- Solves
- Relational join problem
- Time
- O(n m) worstO(n + m + j) average
- Space
- O(n + m) extra
- Where
- j = the number of joining pairs among the tuples read; m = the number of tuples read from S; n = the number of tuples read from R
- Model
- Real RAM
- Properties
- randomizednot exactnot externalnot in placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter J. Haas, Joseph M. Hellerstein, 1999
A ripple join computes an aggregate such as SUM or COUNT over a join for online aggregation: it reports a running estimate with a confidence interval from the first tuples on, and the exact answer when it has read both inputs. It reads both inputs in random order, and at each step it adds a few tuples of each input and joins each new tuple with every tuple already read from the other input, so the pairs it has seen form a growing rectangle. The estimate is the running sum scaled by the fraction of the rectangle seen, and by linearity of expectation it is unbiased. The hash form is a symmetric hash join over random orders. Unlike a nested loops join, which must read all of the inner input for its first outer tuple, a ripple join samples both inputs at once. A wander join samples random paths through indexes instead.
In plain words
You want the total sales of all orders that match a customer in a promotion list, but both tables are large. Instead of waiting for the exact total, you want a good guess now and a better guess every second.
So you take orders and customers in a random order, a few of each at a time. Each new order is checked against the customers you already took, and each new customer against the orders you already took. You add up the sales of every match you find.
If you have taken a tenth of the orders and a tenth of the customers, you have checked about a hundredth of all pairs. So your total, multiplied by 100, is a fair guess of the full total. The guess gets better as you go, and it is exact when you have taken everything.
The problem
The input is two relations and with and , a join condition (a NULL key never matches) and a value for each joining pair, for example a column of . The query asks for over the bag . COUNT is the case , and AVG is SUM divided by COUNT.
The output is a sequence of estimates , one per step, each with a confidence interval, such that each estimate is unbiased and the last one equals .
Cost model. The measure is the work per step in the real RAM, with expected time per hash table operation, and the quality of the estimate after tuples of and tuples of , measured by its variance. The orders of and must be independent and uniformly random, for example because the tables are stored in random order or read through a random permutation.
The algorithm
RIPPLE-JOIN(R, S, v, β_R, β_S) ▷ v(r, s) is the value of a joining pair- 1
put R and S in independent random orders; R_t, S_t ← empty; Σ ← 0 - 2
while some tuple of R or S is not read do - 3
for β_R new tuples r of R, as far as they last: Σ ← Σ + the sum of v(r, s) over s in S_t that join with r; add r to R_t - 4
for β_S new tuples s of S, as far as they last: Σ ← Σ + the sum of v(r, s) over r in R_t that join with s; add s to S_t - 5
τ̂ ← N M / (|R_t| |S_t|) · Σ - 6
h ← z · the square root of the estimated variance of τ̂ - 7
report τ̂ ± h
The pair is the aspect ratio. The square ripple join has . With , the first step reads all of , and the ripple join becomes a nested loops join over a random order of . Lines L3 and L4 can scan the tuples read from the other input (the block or nested-loops form) or look up the key in a hash table on them (the hash form). Both forms add the same pairs, so they give the same estimates.
The variance in line L6 is the first-order part of the formula in the section on correctness, with the variances of the row and column means estimated from the sample. The number comes from the normal distribution, for example for a 95% interval.
Example
Let , written as (key, price), and . The query is the SUM of the price over . The true answer is . Take the square ripple join, and let the random order be the order given.
| step | new tuples | new joining pairs | rectangle | estimate | |
|---|---|---|---|---|---|
| 1 | , | : 3 | 3 | 36 | |
| 2 | , | : 5 | 8 | 24 | |
| 3 | , | : 2, : 3, : 2 | 15 | 20 | |
| 4 | ( is exhausted) | none | 15 | 15 |
The estimate at step 3 is 20, although the sum already holds all 15. The ripple join cannot know that the unread tuple joins with nothing. Over all orders, the mean of the estimate at each step is exactly 15.
A larger run. Let have 200 tuples with keys from 5 values and prices from 1 to 19, and have 200 tuples with keys from the same 5 values, all drawn with seed 5. The true SUM is 79718. Over 200 square ripple joins with different random orders:
| tuples read from each input | mean estimate | standard deviation of the estimate | median half width at 95% | runs whose interval holds 79718 |
|---|---|---|---|---|
| 10 | 79962 | 22178 | 50722 | 193 of 200 |
| 25 | 79050 | 9254 | 22948 | 197 of 200 |
| 50 | 79466 | 5866 | 12656 | 195 of 200 |
| 100 | 80115 | 3150 | 6607 | 193 of 200 |
The exact standard deviation from the variance formula is 21904, 10393, 6039 and 3244 at these four steps. At 100 tuples of each input the ripple join has seen a quarter of the pairs, and the standard deviation of its estimate is about 4% of the answer. These numbers are measurements of this simulation.
Correctness
At each step the running sum is the sum of over all joining pairs in the rectangle , because each pair is added once, when the later of its two tuples is read. A prefix of a random order is a uniform random subset, so a pair is in the rectangle with probability , and the scaled sum has expectation . The exact variance is
where is the variance of the row means , the variance of the column means, and the variance of the rest. When both inputs are read, every factor and is 0 and the estimate is exact. The proofs are in the proof page.
The interval of line L6 uses an estimate of the first two terms and a central limit theorem, so its coverage is close to the nominal level only for large samples. A conservative interval from Hoeffding's inequality needs a bound on the values and is wider. See confidence interval for the general idea.
Proof: The ripple join estimate is unbiased at every step, with an exact variance formula, and it equals the answer when both inputs are readfull
We use the line numbers of the pseudocode. has tuples and has tuples, and each stored tuple is a distinct occurrence. For and let be the value of the pair when the keys are equal and not NULL, and otherwise. The query asks for . COUNT is the case on joining pairs. After step the algorithm has read the sets and of sizes and . These sizes depend only on , , and the aspect ratio , not on the random order. The estimate of line L5 is
Lemma 1 (the running sum covers the rectangle). After step , .
Proof. Line L3 adds a tuple to and adds for every already in . Line L4 adds a tuple and adds for every already in , including the tuples of added in the same step. So each pair of is added once, when the later of its two tuples is added, and no pair outside the rectangle is added. The hash form looks up only the tuples with the same key, which are exactly the pairs with possibly nonzero, so both forms give the same sum.
Theorem 1 (unbiased). If the orders of and are independent and uniformly random, then at every step with .
Proof. A prefix of length of a uniformly random order of is a uniformly random subset of size , so for each , and in the same way . The two orders are independent, so . By Lemma 1 and linearity of expectation,
The estimate of AVG is the ratio of the SUM and COUNT estimates. A ratio of unbiased estimates is not unbiased in general, so the AVG estimate is only consistent.
Theorem 2 (exact variance). Let , , and . Let and , and let
Then, with a term read as 0 when its factor or is 0,
Proof. Write and sum over the rectangle. With the mean of over and the mean of over ,
The function has zero row sums and zero column sums: , and the same for columns.
The three terms are uncorrelated. depends only on and only on , which are independent. Given , each is in with probability , so . So , and in the same way .
The first two terms. is the mean of a simple random sample of size without replacement from the values , so its variance is , and the same holds for .
The third term. . For in , , and ; the same with and for . Then
For fixed , the sum over of equals . So the sum over is . Doing the same over gives
Since , this is . Adding the three variances and multiplying by gives the formula. When the sample is all of , , and the terms with vanish.
The third term falls like , faster than the first two, so for large samples the variance is close to the first two terms. The implementation estimates by the sample variance of over , and in the same way, and uses as the interval. That the interval has coverage close to the nominal level rests on a central limit theorem for large samples. It is an approximation, not a bound for a given .
Theorem 3 (the end is exact, and termination). Each step reads at least one tuple while some tuple is unread, so after at most steps and . Then by Lemma 1, and every term of the variance has a zero factor.
Theorem 4 (work). Let be the number of joining pairs in . With hash tables in expected time per operation, the hash form does expected work up to step , plus per step for the estimate if the sums and of the squared row and column sums are kept up to date. The nested-loops form does comparisons.
Proof. Each read costs one insert and one lookup. Each joining pair is met once (Lemma 1) and changes one row sum and one column sum by , and changes by , computed in . The sample variances follow from these sums and . The nested form compares each new tuple with every tuple read from the other input, which gives comparisons for the rectangle.
The implementation recomputes the sample variances at each step in time, which is simpler and does not change the results.
Complexity
- Work. The hash form does expected work per tuple read and per joining pair found, so the work up to the rectangle is expected . The block form does comparisons for the same rectangle. The variance can be kept up to date in per pair with running sums of squares.
- Variance. For a fixed aspect ratio the variance falls like in the number of tuples read from each input, plus a term in that matters only for small samples. A ratio that reads more from the input whose row means vary more gives a smaller variance for the same work.
- Space. All tuples read stay in memory, , because a later tuple of the other input may join with any of them.
Properties
- Online. An estimate is available after each step, and the user may stop the query at any time.
- Unbiased at every step for SUM and COUNT, when the orders are uniformly random. AVG is a ratio of two estimates and is only consistent.
- Exact at the end. After both inputs are read, the estimate is the answer and the interval has width 0.
- Randomized. The estimates depend on the random orders. With a fixed seed they are repeatable.
- Any join condition. The block form works for any predicate, not only for equality, but it needs comparisons.
Variants and improvements
- Adaptive aspect ratio. Haas and Hellerstein choose the aspect ratio during the run, from the estimated variances of the two inputs, to make the interval shrink fastest for the work done.
- Index ripple join. If has an index on the key, each new tuple of looks up all its matches in at once. This is the case done through the index, and the estimate is then a mean over a random sample of only.
- Hash ripple join out of memory. Luo, Ellmann, Haas and Naughton (2002) extend the hash ripple join to the case where the tuples read no longer fit in memory, by partitioning them to disk in the manner of a Grace hash join.
- More than two inputs. The same idea works for inputs: each step extends a hyper-rectangle, and the estimate scales the sum by the product of the sampling fractions.
- Wander join. A wander join does not read the inputs in order: it walks a random path through indexes from one tuple to a matching tuple, and weights each path by the inverse of its probability.
When to use it
Use a ripple join when a user wants a fast approximate answer to an aggregate over a join of large tables and is ready to stop early, and the tables can be read in random order. It works best when the join has many results, so that a small rectangle already contains many joining pairs. For a join with very few results, most of the early rectangle contains nothing and the interval stays wide for a long time.
Pitfalls
- Input that is not in random order. If the tables are sorted or clustered, a prefix is not a random sample and the estimate is biased. The orders must also be independent of each other.
- Selective joins. When few pairs join, the variance is large compared with , and the interval from the central limit theorem can be too narrow for small samples.
- Reusing the interval at every step. A 95% interval at each step does not give 95% confidence that all intervals hold at once. A user who stops when the interval looks good needs an interval that holds over all steps.
- Memory. The memory grows with the tuples read, as in a symmetric hash join.
- AVG. The AVG estimate is biased for small samples, and its interval needs the delta method for the ratio.
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/ripple-join/. The authors are listed in prov/NQMZP0.jsonl.
"""Ripple join: an online estimate of SUM(value) over the equi-join of R and S.
The tuples of R and S are read in a random order (or in the given order when
rng is None, so that a caller can pass its own permutation). Each step reads
beta_R new tuples of R and beta_S new tuples of S, as far as they last, and
joins each new tuple with every tuple already read from the other input. After
step t the running sum covers exactly the pairs of the rectangle R_n x S_n of
the tuples read so far, and the estimate is
|R| |S| / (n_R n_S) * (sum of value(r, s) over the joining pairs in R_n x S_n).
COUNT is SUM with value 1. The half width of the confidence interval uses the
first-order (delta method) variance
|R|^2 |S|^2 ((1 - n_R/|R|) v_R / n_R + (1 - n_S/|S|) v_S / n_S),
where v_R is the sample variance over r in R_n of the mean value of r against
S_n, and v_S is the same for S. It is an approximation for large samples.
method "hash" keeps a hash table on the key of each input and probes it;
method "nested" compares the new tuple with every tuple read from the other
input. Both give the same running sums. A NULL key (None) never matches.
"""
import math
import random
from collections.abc import Callable, Sequence
from fractions import Fraction
def _sample_var(xs: list) -> float:
if len(xs) < 2:
return 0.0
m = sum(xs) / len(xs)
return sum((x - m) ** 2 for x in xs) / (len(xs) - 1)
def exact_variance(r_rows: Sequence[tuple], s_rows: Sequence[tuple], rkey: Callable, skey: Callable,
value: Callable, n_r: int, n_s: int) -> Fraction:
"""The exact variance of the estimate after reading n_r tuples of R and n_s of S.
With v(r, s) the value of a joining pair (0 otherwise), a(r) and b(s) the
row and column means, mu the overall mean and g = v - a - b + mu:
Var = |R|^2 |S|^2 ((1 - f_R) S_a / n_r + (1 - f_S) S_b / n_s + (1 - f_R)(1 - f_S) S_g / (n_r n_s)),
where f_R = n_r / |R|, S_a = sum (a - mu)^2 / (|R| - 1), and the same for
b, and S_g = sum g^2 / ((|R| - 1)(|S| - 1)). A term with a zero factor
(1 - f) is 0, also when |R| = 1 or |S| = 1.
"""
big_r, big_s = len(r_rows), len(s_rows)
def v(r, s):
kr, ks = rkey(r), skey(s)
return Fraction(value(r, s)) if kr is not None and ks is not None and kr == ks else Fraction(0)
mat = [[v(r, s) for s in s_rows] for r in r_rows]
mu = sum(map(sum, mat)) / (big_r * big_s)
a = [sum(row) / big_s for row in mat]
b = [sum(mat[i][j] for i in range(big_r)) / big_r for j in range(big_s)]
fr, fs = Fraction(n_r, big_r), Fraction(n_s, big_s)
var = Fraction(0)
if fr != 1:
var += (1 - fr) * sum((x - mu) ** 2 for x in a) / (big_r - 1) / n_r
if fs != 1:
var += (1 - fs) * sum((x - mu) ** 2 for x in b) / (big_s - 1) / n_s
if fr != 1 and fs != 1:
sg = sum((mat[i][j] - a[i] - b[j] + mu) ** 2 for i in range(big_r) for j in range(big_s))
var += (1 - fr) * (1 - fs) * sg / ((big_r - 1) * (big_s - 1)) / (n_r * n_s)
return (big_r * big_s) ** 2 * var
def ripple_join(r_rows: Sequence[tuple], s_rows: Sequence[tuple], rkey: Callable, skey: Callable,
value: Callable, aspect: tuple = (1, 1), rng: random.Random | None = None,
method: str = "hash", z: float = 1.96) -> list:
"""Run the ripple join to the end and return one snapshot per step.
A snapshot is a dict with n_r, n_s, sum (exact, over the rectangle read),
estimate (a Fraction), half_width (a float) and pairs (pairs that joined).
"""
if method not in ("hash", "nested"):
raise ValueError("method must be 'hash' or 'nested'")
big_r, big_s = len(r_rows), len(s_rows)
r_order, s_order = list(r_rows), list(s_rows)
if rng is not None:
rng.shuffle(r_order) # @line L1
rng.shuffle(s_order)
seen = ([], [])
tables = ({}, {})
rowsum = ([], []) # rowsum[0][i]: sum of value(r_i, s) over s read so far
total = 0
pairs = 0
n = [0, 0]
snaps = []
keyf = (rkey, skey)
orders = (r_order, s_order)
if big_r == 0 or big_s == 0:
return [{"n_r": 0, "n_s": 0, "sum": 0, "estimate": Fraction(0), "half_width": 0.0, "pairs": 0}]
def add(side: int, t: tuple) -> None:
nonlocal total, pairs
other = 1 - side
k = keyf[side](t)
mine = 0
if method == "hash":
matches = tables[other].get(k, ()) if k is not None else ()
else:
matches = [j for j, u in enumerate(seen[other])
if k is not None and keyf[other](u) is not None and keyf[other](u) == k]
for j in matches:
u = seen[other][j]
v = value(t, u) if side == 0 else value(u, t)
mine += v
rowsum[other][j] += v
pairs += 1
total += mine
idx = len(seen[side])
seen[side].append(t)
rowsum[side].append(mine)
if k is not None:
tables[side].setdefault(k, []).append(idx)
n[side] += 1
while n[0] < big_r or n[1] < big_s: # @line L2
for _ in range(aspect[0]):
if n[0] < big_r:
add(0, orders[0][n[0]]) # @line L3
for _ in range(aspect[1]):
if n[1] < big_s:
add(1, orders[1][n[1]]) # @line L4
if n[0] == 0 or n[1] == 0:
continue
est = Fraction(big_r * big_s * total, n[0] * n[1]) # @line L5
v_r = _sample_var([x / n[1] for x in rowsum[0]])
v_s = _sample_var([x / n[0] for x in rowsum[1]])
var = (big_r * big_s) ** 2 * ((1 - n[0] / big_r) * v_r / n[0] + (1 - n[1] / big_s) * v_s / n[1])
half = z * math.sqrt(max(var, 0.0)) # @line L6
snaps.append({"n_r": n[0], "n_s": n[1], "sum": total, "estimate": est,
"half_width": half, "pairs": pairs}) # @line L7
return snaps
test_ripple_join.py 100 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ripple-join/. The authors are listed in prov/NQMZP0.jsonl.
import itertools
import random
from fractions import Fraction
from ripple_join import exact_variance, ripple_join
KEY = lambda t: t[0]
PRICE = lambda r, s: r[2]
ONE = lambda r, s: 1
def exact(r_rows, s_rows, value):
return sum(value(r, s) for r in r_rows for s in s_rows
if r[0] is not None and s[0] is not None and r[0] == s[0])
R_EX = [(1, "r1", 3), (2, "r2", 5), (1, "r3", 2), (3, "r4", 4)]
S_EX = [(1, "s1", 0), (2, "s2", 0), (1, "s3", 0)]
def test_example() -> None:
snaps = ripple_join(R_EX, S_EX, KEY, KEY, PRICE)
assert [(x["n_r"], x["n_s"]) for x in snaps] == [(1, 1), (2, 2), (3, 3), (4, 3)]
assert [x["sum"] for x in snaps] == [3, 8, 15, 15]
assert [x["estimate"] for x in snaps] == [36, 24, 20, 15]
assert exact(R_EX, S_EX, PRICE) == 15 and snaps[-1]["half_width"] == 0.0
def test_unbiased_over_all_orders() -> None:
# The mean of the estimate over all orders of R and S equals the true value at every step.
s_null = S_EX + [(None, "s4", 0)]
for s_rows, value in ((S_EX, PRICE), (s_null, ONE), (s_null, PRICE)):
truth = exact(R_EX, s_rows, value)
for aspect in ((1, 1), (2, 1), (1, 2), (3, 2)):
total = None
count = 0
for pr in itertools.permutations(R_EX):
for ps in itertools.permutations(s_rows):
est = [x["estimate"] for x in ripple_join(list(pr), list(ps), KEY, KEY, value, aspect)]
total = est if total is None else [a + b for a, b in zip(total, est)]
count += 1
assert all(Fraction(t, count) == truth for t in total)
def test_exact_variance_over_all_orders() -> None:
s_null = S_EX + [(None, "s4", 0)]
for s_rows, value in ((S_EX, PRICE), (s_null, PRICE), (s_null, ONE)):
truth = exact(R_EX, s_rows, value)
for aspect in ((1, 1), (2, 1)):
sq = None
count = 0
for pr in itertools.permutations(R_EX):
for ps in itertools.permutations(s_rows):
snaps = ripple_join(list(pr), list(ps), KEY, KEY, value, aspect)
dev = [(x["estimate"] - truth) ** 2 for x in snaps]
sq = dev if sq is None else [a + b for a, b in zip(sq, dev)]
count += 1
for x, total in zip(snaps, sq):
want = exact_variance(R_EX, s_rows, KEY, KEY, value, x["n_r"], x["n_s"])
assert Fraction(total, count) == want
def test_hash_equals_nested() -> None:
rng = random.Random(2)
for trial in range(30):
dom = rng.choice([3, 4, 5])
keys = list(range(dom)) + [None]
r = [(rng.choice(keys), i, rng.randrange(10)) for i in range(rng.randrange(0, 40))]
s = [(rng.choice(keys), i, 0) for i in range(rng.randrange(0, 40))]
aspect = rng.choice([(1, 1), (2, 1), (1, 3)])
a = ripple_join(r, s, KEY, KEY, PRICE, aspect, random.Random(trial), "hash")
b = ripple_join(r, s, KEY, KEY, PRICE, aspect, random.Random(trial), "nested")
assert a == b
assert a[-1]["estimate"] == exact(r, s, PRICE)
assert a[-1]["pairs"] == exact(r, s, ONE)
def test_empty_inputs() -> None:
assert ripple_join([], S_EX, KEY, KEY, PRICE)[-1]["estimate"] == 0
assert ripple_join(R_EX, [], KEY, KEY, PRICE)[-1]["estimate"] == 0
def test_mean_and_coverage() -> None:
rng = random.Random(5)
r = [(rng.randrange(5), i, rng.randrange(1, 20)) for i in range(200)]
s = [(rng.randrange(5), i, 0) for i in range(200)]
truth = exact(r, s, PRICE)
runs = 120
for step in (25, 50):
ests = []
covered = 0
for t in range(runs):
x = ripple_join(r, s, KEY, KEY, PRICE, rng=random.Random(1000 + t))[step - 1]
ests.append(x["estimate"])
covered += abs(x["estimate"] - truth) <= x["half_width"]
assert abs(sum(ests) / runs - truth) <= 0.03 * truth
assert covered >= 0.85 * runs
History
Hellerstein, Haas and Wang (1997) proposed online aggregation for single-table queries in a relational system, with running estimates and confidence intervals. Haas and Hellerstein (1999) introduced ripple joins to extend online aggregation to joins, as a family that includes block, index and hash ripple joins, and they gave confidence intervals based on a central limit theorem and a rule for choosing the aspect ratio during the run. Luo, Ellmann, Haas and Naughton (2002) made the hash ripple join scale beyond memory. Later work, such as wander join, sampled join paths through indexes instead of rectangles.
References
- Peter J. Haas and Joseph M. Hellerstein, Ripple joins for online aggregation, SIGMOD 1999, pages 287 to 298, the ripple join family (block, index and hash ripple joins), the aspect ratios and their adaptive choice, and the confidence intervals based on a central limit theorem
- Joseph M. Hellerstein, Peter J. Haas and Helen J. Wang, Online aggregation, SIGMOD 1997, pages 171 to 182, the online aggregation interface with running estimates and confidence intervals for single-table queries
- Gang Luo, Curt J. Ellmann, Peter J. Haas and Jeffrey F. Naughton, A scalable hash ripple join algorithm, SIGMOD 2002, pages 252 to 262, the hash ripple join when the tuples read no longer fit in memory
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 NQMZP0 Edit this page History Report an error Markdown