Techniqueadvanced
Online aggregation
Also called progressive aggregation.
Read the input of an aggregate query in random order and keep a running estimate of each answer with a confidence interval, so that the user can stop as soon as the answer is good enough.
Online aggregation is the technique of answering an aggregate query, such as an AVG or SUM with GROUP BY, with an estimate that improves while the query runs, instead of one exact answer at the end. The system reads the input in random order, so that the tuples read so far are a random sample, and after each batch it reports for each group an estimate and a confidence interval from a central limit theorem or from Hoeffding's inequality. The user can stop the query, or one group, as soon as the interval is narrow enough, and if nobody stops it, the last estimate is the exact answer. A plain group-by aggregation gives nothing until the end. A ripple join extends the technique to joins.
In plain words
You want the average salary in each department of a large company. The exact answer needs every record, which takes an hour. But after a few thousand random records you already know the averages quite well.
So the system takes the records in a random order and shows you the running average of each department, with a range that says how sure it is, for example "52,300, give or take 800". Every second the numbers change a little and the ranges get smaller. Small departments have wider ranges, because fewer of their records have come in.
When the ranges are small enough for your purpose, you stop. If you never stop, the system reads everything, and the last numbers are the exact ones.
When it applies
- The query computes SUM, COUNT or AVG, which are sums or ratios of sums. Each estimate is a scaled sample sum. MIN, MAX and COUNT DISTINCT do not have simple unbiased estimates from a sample and need other methods.
- The input can be read in random order: the table is stored in random order, it is read through a random permutation of its pages or tuples, or an index gives random access. A prefix of a random order is a uniform random sample without replacement.
- An approximate answer early is worth more than an exact answer late, as in data exploration. Results that must be exact, such as a bill, need the full run.
- Each step of the query plan can output partial results, so the plan must not have a blocking operator, such as a sort, before the aggregate.
The template
ONLINE-AGGREGATE(T, g, x, z) ▷ SELECT g, SUM(x), COUNT(*), AVG(x) FROM T GROUP BY g, with |T| = N- 1
read T in a random order - 2
for i ← 1 to N do - 3
t ← the i-th tuple; in the group h = g(t): c_h ← c_h + 1, s_h ← s_h + x(t), q_h ← q_h + x(t)² - 4
every so often, for each group h: report SUM ≈ (N/i) s_h, COUNT ≈ (N/i) c_h, AVG ≈ s_h / c_h, each with a half width - 5
at i = N every estimate is the exact answer
For AVG, the large-sample half width is , where is the sample variance of the group and for 95%. If every value lies in , Hoeffding's inequality gives the conservative half width for confidence . Hoeffding (1963) showed that the bound also holds for sampling without replacement.
Why it works. After tuples, the tuples read are a uniform random subset of size of , so each tuple is in it with probability . The SUM estimate is , and by linearity of expectation its mean is the true sum of the group. The COUNT estimate is the case . For AVG, given that tuples of group have been read, every set of tuples of the group is equally likely, so the tuples read from the group are a random sample of it, and their mean is an unbiased estimate of the group mean. The sample mean of a random sample of size without replacement from values has variance , which the formula estimates with and for . At the sample is the whole table.
Cost. Each tuple costs updates of three numbers in its group, the same as a hash aggregation. Each report costs for groups. The width of each interval shrinks like , so halving the width of a group needs four times as many of its tuples.
Example. Let hold 10 tuples (group, ): . The exact answers are AVG, AVG and SUM. Let the random order be , with a report every 2 tuples.
| tuples read | AVG estimate | AVG estimate | SUM estimate |
|---|---|---|---|
| 2 | 7 | 12 | 60 |
| 4 | 6 | 10 | 50 |
| 6 | 5.5 | 10 | 33.3 |
| 8 | 5.2 | 11.33 | 42.5 |
| 10 | 5.33 | 11 | 44 |
At the large-sample half width of AVG is 0.94 and that of AVG is 1.55. With and , Hoeffding's half widths are 12.15 and 15.68: they are safe for any data in the range, but much wider. On 300 random orders of a table of 200 tuples in 3 groups with values from 0 to 99, the Hoeffding intervals held the true group averages in every case after 20, 50 and 100 tuples, and the large-sample intervals held in 87%, 93% and 93% of the cases. These are measurements of a simulation.
Classic examples
- Single-table GROUP BY. Hellerstein, Haas and Wang (1997) gave the interface: a running estimate and interval per group, with a control to stop a group whose estimate is good enough, so that the remaining work goes to the other groups.
- Joins. A ripple join reads both inputs of a join in random order and scales the sum over the pairs seen, which keeps the SUM estimate unbiased.
- Joins through indexes. A wander join samples random join paths through indexes and weights each path by the inverse of its probability, in the manner of a Horvitz and Thompson estimator.
- Approximate query answering from samples. A system can keep a stratified sample or a reservoir sample of each table and answer from it first, the same estimators applied to a stored sample.
Variations
- Fair access to groups. In a random order, a small group gets few tuples and its interval stays wide. If an index on the grouping column exists, the system can read the groups in turn through the index (index striding), so that each group gets tuples at a rate that the user controls.
- Conservative and large-sample intervals. Hoeffding intervals hold for every sample size but need bounds on the values and are wide. Intervals from the central limit theorem are narrower and need large samples.
- Intervals over time. A user who watches the interval and stops when it looks good is testing at many times. An interval that holds at all times at once needs a wider bound, for example a union bound over the reporting times.
- Block sampling. Reading random pages instead of random tuples is much cheaper on disk, but tuples on one page are often alike, which makes the variance larger than the formula for tuples says.
Pitfalls
- Input in storage order. If the table is sorted or clustered, for example by date, a prefix is not a random sample, and the estimates are biased until the end.
- AVG of a group with one tuple. The sample variance needs two tuples. With one, the large-sample interval has no meaning, and the implementation reports width 0, which must not be read as certainty.
- Small groups and outliers. A group with few tuples, or with a few very large values, has an estimate that can be far off with a narrow interval from the central limit theorem. Hoeffding's interval needs the bounds of the column, which are often only known loosely.
- Blocking operators. A sort, a hash join that builds first, or an ORDER BY before the aggregate stops the running estimates until it finishes.
- The final answer. The estimates are exact only at . A group that has had all its tuples read before the end is exact too, but the system cannot know that without the group sizes.
Code
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/online-aggregation/. The authors are listed in prov/NT88SJ.jsonl.
"""Online aggregation of SELECT g, SUM(x), COUNT(*), AVG(x) FROM T GROUP BY g.
The table is read in a random order (or in the given order when rng is None).
After i of the N tuples, for each group seen so far:
SUM estimate N / i * s_g (s_g: sum of x in the group so far)
COUNT estimate N / i * c_g (c_g: tuples of the group so far)
AVG estimate s_g / c_g
The SUM and COUNT estimates are unbiased. The AVG estimate is unbiased given
c_g >= 1, because the tuples of a group seen so far are then a uniform random
subset of the group. Two half widths are given for AVG: a large-sample one,
z * sqrt((1 - i/N) * var_g / c_g), and a conservative one from Hoeffding's
inequality for values in [lo, hi], (hi - lo) * sqrt(ln(2 / delta) / (2 c_g)),
which also holds for sampling without replacement. When i = N every estimate
is the exact answer.
"""
import math
import random
from collections.abc import Callable, Sequence
from fractions import Fraction
def online_aggregate(rows: Sequence[tuple], group: Callable, value: Callable, every: int = 1,
rng: random.Random | None = None, z: float = 1.96,
bounds: tuple | None = None, delta: float = 0.05) -> list:
"""Read rows one at a time and return a snapshot after every `every` tuples and at the end.
A snapshot is (i, {g: estimates}); the estimates of a group are a dict with
count, sum, avg (Fractions), half_clt and half_hoeffding (floats, the
latter only when bounds = (lo, hi) is given).
"""
order = list(rows)
big_n = len(order)
if rng is not None:
rng.shuffle(order) # @line L1
cnt: dict = {}
tot: dict = {}
sq: dict = {}
snaps = []
for i, t in enumerate(order, start=1): # @line L2
g, x = group(t), value(t)
cnt[g] = cnt.get(g, 0) + 1
tot[g] = tot.get(g, 0) + x
sq[g] = sq.get(g, 0) + x * x # @line L3
if i % every and i != big_n:
continue
est = {}
for h in sorted(cnt, key=repr):
c, s = cnt[h], tot[h]
avg = Fraction(s, c)
var = float((sq[h] - c * avg * avg) / (c - 1)) if c > 1 else 0.0
e = {"count": Fraction(big_n * c, i), "sum": Fraction(big_n * s, i), "avg": avg,
"half_clt": z * math.sqrt(max(0.0, (1 - i / big_n) * var / c))}
if bounds is not None:
lo, hi = bounds
e["half_hoeffding"] = 0.0 if i == big_n else (hi - lo) * math.sqrt(math.log(2 / delta) / (2 * c))
est[h] = e # @line L4
snaps.append((i, est))
return snaps # @line L5
test_online_aggregation.py 86 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/online-aggregation/. The authors are listed in prov/NT88SJ.jsonl.
import itertools
import random
from fractions import Fraction
from online_aggregation import online_aggregate
G = lambda t: t[0]
X = lambda t: t[1]
T_EX = [("a", 4), ("b", 10), ("a", 6), ("a", 2), ("b", 14), ("a", 8), ("b", 12), ("a", 5), ("a", 7), ("b", 8)]
def exact(rows):
out = {}
for g, x in rows:
c, s = out.get(g, (0, 0))
out[g] = (c + 1, s + x)
return {g: {"count": c, "sum": s, "avg": Fraction(s, c)} for g, (c, s) in out.items()}
def test_example() -> None:
snaps = online_aggregate(T_EX, G, X, every=2, rng=random.Random(1), bounds=(0, 20))
assert [i for i, _ in snaps] == [2, 4, 6, 8, 10]
assert [e["a"]["avg"] for _, e in snaps] == [7, 6, Fraction(11, 2), Fraction(26, 5), Fraction(16, 3)]
assert [e["b"]["avg"] for _, e in snaps] == [12, 10, 10, Fraction(34, 3), 11]
assert [e["b"]["sum"] for _, e in snaps] == [60, 50, Fraction(100, 3), Fraction(85, 2), 44]
last = snaps[-1][1]
assert last["b"]["half_clt"] == 0.0 and last["b"]["half_hoeffding"] == 0.0
def test_exact_at_the_end() -> None:
rng = random.Random(4)
for trial in range(40):
rows = [(rng.randrange(rng.choice([1, 3, 5])), rng.randrange(-5, 50)) for _ in range(rng.randrange(1, 120))]
i, est = online_aggregate(rows, G, X, every=7, rng=random.Random(trial))[-1]
assert i == len(rows)
want = exact(rows)
assert est.keys() == want.keys()
for g in want:
assert {k: est[g][k] for k in ("count", "sum", "avg")} == want[g]
def test_unbiased_over_all_orders() -> None:
rows = [("a", 4), ("b", 10), ("a", 6), ("a", 2), ("b", 14), ("a", 9), ("c", 1)]
want = exact(rows)
n = len(rows)
sums = {(i, g): Fraction(0) for i in range(1, n + 1) for g in want}
counts = dict(sums)
avg_sum = dict(sums)
avg_n = {k: 0 for k in sums}
orders = 0
for perm in itertools.permutations(rows):
orders += 1
for i, est in online_aggregate(list(perm), G, X):
for g in want:
e = est.get(g)
if e is not None:
sums[i, g] += e["sum"]
counts[i, g] += e["count"]
avg_sum[i, g] += e["avg"]
avg_n[i, g] += 1
for (i, g), total in sums.items():
assert total / orders == want[g]["sum"]
assert counts[i, g] / orders == want[g]["count"]
# AVG is unbiased given that the group has been seen.
assert avg_sum[i, g] / avg_n[i, g] == want[g]["avg"]
def test_interval_coverage() -> None:
rng = random.Random(9)
rows = [(rng.randrange(3), rng.randrange(0, 100)) for _ in range(200)]
mu = {g: e["avg"] for g, e in exact(rows).items()}
for at in (50, 100):
clt = hoeff = total = 0
for t in range(150):
i, est = online_aggregate(rows, G, X, every=at, rng=random.Random(t), bounds=(0, 99))[0]
assert i == at
for g, e in est.items():
err = abs(e["avg"] - mu[g])
total += 1
clt += err <= e["half_clt"]
hoeff += err <= e["half_hoeffding"]
assert hoeff >= 0.95 * total
assert clt >= 0.85 * total
Exercises
- Show that the COUNT estimate is unbiased, and compute its variance for a group of size from the formula for sampling without replacement.
- Show that the AVG estimate is unbiased given , but that the ratio of two unbiased estimates is not unbiased in general for a ratio of two unknown sums.
- Values lie in . How many tuples of a group does Hoeffding's interval need for a half width of 1 at 95%? How many does the large-sample interval need when the standard deviation of the group is 10?
- A table is stored sorted by its aggregated column. Describe the running AVG estimate in storage order, and explain why its interval does not hold.
References
- Joseph M. Hellerstein, Peter J. Haas and Helen J. Wang, Online aggregation, SIGMOD 1997, pages 171 to 182, the online aggregation interface (running estimates, confidence intervals, stopping a group) for single-table aggregate queries with GROUP BY
- Peter J. Haas and Joseph M. Hellerstein, Ripple joins for online aggregation, SIGMOD 1999, pages 287 to 298, online aggregation over joins with ripple joins and confidence intervals based on a central limit theorem
- Wassily Hoeffding, Probability inequalities for sums of bounded random variables, Journal of the American Statistical Association 58(301), 1963, pages 13 to 30, the bound for sums of bounded independent variables and its extension to sampling without replacement from a finite population
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag NT88SJ Edit this page History Report an error Markdown