Algorithmcore
Parallel hash join
Also called partitioned parallel hash join, Gamma hash join.
Hash-partition both inputs across the nodes on the join key in one round of messages, then let each node join its pair of partitions locally. A frequent key value puts all its work on one node.
- Solves
- Relational join problem
- Time
- O(n/p + L + D) worst · expected
- Space
- O(n) extra
- Counts
- communication O(n) worstcommunication n(p - 1)/p expectedmessages p(p - 1) worst
- Where
- D = the largest number of output tuples at one node; L = the largest number of input tuples at one node after the redistribution; n = the number of input tuples, |R| + |S|; p = the number of nodes; z = the number of output tuples
- Properties
- deterministicexactnot in placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Masaru Kitsuregawa, Hidehiko Tanaka, Tohru Moto oka, David J. DeWitt, Robert H. Gerber, 1983
The parallel hash join computes the equi-join on a shared-nothing machine of nodes. Every node sends each of its tuples to the node that a hash function of the join key chooses, so that tuples with the same key meet at the same node, and then every node runs an ordinary hash join on what it received. It is the parallel form of the Grace hash join: Grace puts the hash partitions on one disk and joins them one after the other, while this algorithm puts them on different nodes and joins them at the same time. The method is a direct use of hash partitioning, and it is the database form of the reduce-side join of MapReduce.
In plain words
Ten clerks share a big pile of orders and a big pile of customer cards. Each clerk has a part of each pile on the desk. To match orders with customers, they agree on a rule: the last digit of the customer number tells which clerk gets the paper. Every clerk walks through the papers on the desk and hands each one to the clerk that the rule names. After that, all papers with the same customer number lie on one desk. Each clerk now matches the papers on the desk alone, and no clerk needs to talk to another again.
The plan works well when the papers spread evenly. If half of the orders belong to one customer, one clerk gets half of the work and the other clerks wait.
The problem
The input is two bags and , spread over nodes: node holds the parts and , and is the bag union of the . The output is the natural join under bag semantics, as on the relational join problem: if a tuple of matches a tuple of on the common attributes , the output holds once for each pair of copies, and a NULL in matches nothing. A routing key is a nonempty subset of , often all of . The output may stay spread over the nodes.
Cost model. The nodes share no memory and no disk, and send messages over a network. The cost has three parts: the number of tuples sent from one node to a different node, the number of messages, and the number of communication rounds. Local work is counted apart, as the largest load on one node, because the slowest node decides when the join ends. The page uses for the number of input tuples and for the number of output tuples. In the BSP model, the redistribution is one superstep whose -relation is the largest number of tuples that one node sends or receives.
The algorithm
PARALLEL-HASH-JOIN(R_0..R_{p-1}, S_0..S_{p-1}, K, h) ▷ node i holds R_i and S_i- 1
for each node i = 0, ..., p - 1 do in parallel ▷ redistribution, one round - 2
for each tuple r of R_i do send r to node h(r[K]) mod p - 3
for each tuple s of S_i do send s to node h(s[K]) mod p - 4
for each node j = 0, ..., p - 1 do in parallel ▷ local join phase - 5
R'_j, S'_j ← the tuples of R and of S that node j received - 6
build a hash table on R'_j with the key r[J] - 7
for each s in S'_j and each r in the bucket of s with r[J] = s[J] do output r · s at node j - 8
return the bag union of the outputs of all nodes
Lines L1 to L3 are the redistribution phase, also called the shuffle. A tuple whose target is its own node does not use the network. All sends go out in the same round, so the cost is one round no matter how many nodes there are. Lines L4 to L7 are the build and probe phases of the hash join, done at each node on its own data. If does not fit in the memory of node , the node runs a Grace or hybrid hash join instead; this changes the local disk cost, not the network cost.
The function in line L2 must be the same at every node, and it must be computed from the key value only. The local hash table in line L6 should use a different hash function than : every key at node has the same value of modulo , so a table indexed by modulo a multiple of would use only a fraction of its buckets.
Example
Let and , so the target of key is . has the tuples to with the keys , and has the tuples to with the keys . The tuples start in round robin order: tuple number is at node .
| node | holds at the start | receives in lines L1 to L3 | local output |
|---|---|---|---|
| 0 | (3), (1), (2); (1), (8) | ; | : 1 tuple |
| 1 | (1), (5), (6); (4), (5) | ; | key 1: , key 4: 1; 5 tuples |
| 2 | (4), (9); (1), (3) | ; | : 1 tuple |
Only , and are already at their target node, so 11 of the 14 tuples cross the network, in 6 messages, one for each ordered pair of different nodes. The nodes hold 4, 6 and 4 tuples after the shuffle and output 1, 5 and 1 tuples, which make the 7 tuples of . For comparison, a broadcast of to the two other nodes sends 16 tuples, and a broadcast of sends 12.
Skew changes the picture. Take , 12 tuples of and 8 tuples of , all with the key 7, placed round robin. Every tuple goes to node . That node holds all 20 tuples and computes all 96 output tuples, and the other three nodes do nothing. The tests of the implementation check both runs.
Correctness
Two tuples that match agree on , so they agree on , have the same value of , and are sent to the same node. Each copy of a tuple is sent to exactly one node, so each matching pair is joined at exactly one node, by the hash join of lines L6 and L7, and the bag union of line L8 has the right count for every output tuple. The full proof, with the network cost and the skew bound, is in the proof page.
Proof: The parallel hash join returns the bag join and sends each tuple at most oncefull
We use the line numbers of the pseudocode on the page. The inputs are bags. is the bag union of its parts , and is the bag union of . The routing key is a nonempty set of attributes that and have in common, and is the set of all common attributes, so . The output is the bag in which the tuple (the tuple extended by the attributes of outside ) has as many copies as there are pairs of occurrences with and no NULL in . We treat each stored copy of a tuple as a distinct occurrence. The hash function is any function from key values to the integers. It need not be injective or uniform.
Lemma 1 (routing). After lines L1 to L3, every occurrence of and of is at exactly one node. An occurrence is at node , and an occurrence is at node .
Proof. Lines L1 and L2 visit each node once and each occurrence of once, and send it to one node. The parts together hold each occurrence of exactly once, so each occurrence of is sent once. Nothing is sent twice or dropped, because the simulation does not lose messages. The same holds for by line L3. The target node is the value that the line computes.
Lemma 2 (co-location). If , then and are at the same node after line L3.
Proof. , so gives . Then , because is a function. By Lemma 1 both occurrences are at that node.
Theorem 1 (correctness). The bag that line L8 returns is .
Proof. Fix a node , and let and be the occurrences that it holds after line L3. Lines L6 and L7 are the hash join of the page hash join on and with the key : line L6 puts each occurrence of whose key has no NULL into the bucket of its key, once, and line L7 meets each occurrence of once and outputs for each occurrence in the bucket of . A NULL in finds no bucket, because no key in the table has a NULL. So node outputs one copy of for each pair in with and no NULL in . This is the bag .
Now take any matching pair of . By Lemma 2, both are at one node , so the pair appears in . By Lemma 1, each occurrence is at only one node, so the pair appears at no other node. Pairs that do not match appear nowhere. So the bag union of the local outputs, which line L8 returns, has exactly one copy of for each matching pair. That is .
Theorem 2 (termination). The algorithm stops after steps of work in total, where counts occurrences and , if each insert and each lookup of a bucket takes steps plus the length of the bucket that it scans.
Proof. Lines L1 to L3 do one send per occurrence: sends. Line L6 does inserts at node , and these add up to over all nodes by Lemma 1. Line L7 does lookups, which add up to . The work of the lookups beyond each is the number of matching pairs they output, which adds up to by Theorem 1, plus the tuples with other keys in the same bucket. With a table that keeps one bucket per distinct key, as the implementation does, there are no such tuples. Every loop runs over a finite bag, so the algorithm stops.
Theorem 3 (network cost). The algorithm uses one round of communication. It sends exactly the occurrences of and whose home node differs from , so at most tuples, and at most messages if the tuples from node to node go in one message.
Proof. By Lemma 1, each occurrence is sent once, from its home node to its target node, and only the sends between different nodes use the network. All sends happen in lines L1 to L3, before any node starts line L4, so they form one round. The messages are the ordered pairs with that carry at least one tuple, and there are such pairs.
Theorem 4 (expected balance). Suppose that maps the distinct key values to nodes independently and uniformly at random, and that the placement of the parts does not depend on . Then each node holds occurrences in expectation after line L3. If the home node of each occurrence is also independent of its key and uniform, the expected number of tuples sent is .
Proof. An occurrence goes to node with probability , so by linearity of expectation node receives occurrences in expectation. An occurrence stays at home when its target equals its home node, which happens with probability under the second assumption. So it is sent with probability , and the expected number of sent tuples is .
Theorem 5 (skew bound). Let be a value of , and let and be the numbers of occurrences of and with key . Whatever is, one node holds at least occurrences after line L3, and if the tuples with key also agree on , that node outputs at least tuples.
Proof. All these occurrences have the same value of , so by Lemma 1 they go to the same node . If they also agree on , every pair of an occurrence and an occurrence among them matches, and by the proof of Theorem 1 the node outputs each such pair.
Theorem 4 says that the expected load is balanced. It does not bound the largest load. Theorem 5 shows that no choice of helps when one key value is frequent: the time of the slowest node is at least proportional to , so with the speed-up over one node is at most about 2, whatever is.
Complexity
- Network (theorem). Each tuple is sent at most once, so at most tuples cross the network, in one round and at most messages. If maps keys to nodes uniformly and independently, and the start node of a tuple does not depend on its key, a tuple stays home with probability , and the expected number of tuples sent is . If both inputs are already hash-partitioned on with the same , nothing is sent.
- Local work. Node does expected work, where is its output. The join ends when the slowest node ends, so the time is , where is the scan of the local parts (when they start even), the largest load after the shuffle and the largest local output.
- Balance (theorem and its limit). Under a uniform random , each node receives tuples in expectation. When every key value has few tuples, the largest load is close to with high probability, by a Chernoff bound. But if one key value has tuples in and in , one node receives all of them and outputs tuples, whatever is. See data skew.
- Memory. In total for the inputs; node needs room for the hash table on .
Properties
- One round. The algorithm talks once. Later nodes do not wait on one another, so the method scales with when the keys spread well. Gamma reported join speedup that was close to linear on a 32 node machine (a measurement, DeWitt et al. 1990).
- Equality only. Hash routing can only bring together tuples with equal keys. A band join or an inequality join needs range routing or a broadcast.
- Exact under bags. Duplicates and their counts survive, because each copy is routed once and joined once.
- Pipelined. A node can start the probe of line L7 as soon as it has all its tuples of , so in Gamma the build relation is redistributed first and the probe relation streams after it.
- Skew sensitive. The load of a node is the sum over the key values that sends to it. Uniform balances the number of distinct keys, not the number of tuples.
Variants and improvements
- Grace and Hybrid on each node. DeWitt and Gerber (1985) made multiprocessor versions of the Grace and the Hybrid hash joins. In their Grace version, nodes with disks partition the inputs and send buckets to diskless joining nodes. In the Hybrid version, every node has a disk and both partitions and joins. A tuple whose bucket belongs to the node that partitions it goes at once into the local build or probe, so the Hybrid version puts less load on the network than the Grace version.
- Bit vector filters. A node can send a bit vector of the keys of to the nodes of before the probe, so that tuples of with no match are not sent. This is a Bloom filter used as in the Bloom join. DeWitt and Gerber report that the filter helped all the join methods they measured.
- Broadcast join. If is small, send all of to every node and leave where it is. The cost is tuples, and skew in does no harm. This is the map-side join of MapReduce.
- Co-located join. If both relations are already partitioned on the join key with the same function, as a horizontal fragmentation can arrange, lines L1 to L3 send nothing.
- Skew handling. Find the frequent key values first, split the tuples of a frequent value on one side over several nodes and send the matching tuples of the other side to all of them. The data skew page lists such methods.
- More than two relations. A chain of parallel hash joins shuffles once per join. The HyperCube or Shares join replicates tuples so that a multiway join needs only one round.
- Operators in a plan. The exchange operator packs lines L1 to L3 into a plan operator, so that the local join stays a serial operator.
When to use it
Use it for a large equi-join of two relations that are not partitioned on the join key, on a cluster of nodes that share nothing. If one relation is much smaller than the other, compare for a broadcast with about for the shuffle and pick the smaller one. If both relations are already partitioned on the key, join in place. If the key has a few very frequent values, add a skew step or use a broadcast.
Pitfalls
- Different hash functions at different nodes. Line L2 and line L3 must use the same and the same at every node. A function that depends on a per process seed, such as the string hash of some languages, sends equal keys to different nodes and loses matches.
- Routing on more attributes than the join uses. must be a subset of the join attributes . If holds an attribute outside , two matching tuples can go to different nodes.
- The same hash for routing and for the local table. All keys at node have the same . A local table indexed by with a multiple of puts them all in a few buckets.
- Counting balance by keys. A uniform hash function gives each node about the same number of distinct keys. The number of tuples can still be far from even. Measure the load in tuples.
- Memory per node. The build side must fit in the memory of each node, not in the total memory. DeWitt and Gerber point out that a bucket can overflow the memory of its node even when the smaller relation fits in the total memory.
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)
parallel_hash_join.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parallel-hash-join/. The authors are listed in prov/XNDHHS.jsonl.
"""Partitioned parallel hash join on a simulated shared-nothing machine.
The machine has p nodes. Node i holds a part R_i of R and a part S_i of S,
each a dbrel.Relation in bag mode. The join is the natural join on the
common attributes; the tuples are routed by a hash of the key attributes,
which must be common attributes (by default all of them). The simulation
runs in one thread. It counts every tuple that goes from one node to a
different node, and one message for each pair of nodes (i, j) with i != j
that has at least one tuple to send from i to j. All sends happen in one
communication round. Local work is not counted in the network cost.
A NULL in a key attribute never matches, as in SQL. Such a tuple is still
routed, and the probe ignores it.
"""
from collections import Counter
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
import zlib
from dbrel import Relation
def stable_hash(key: tuple) -> int:
"""A hash that does not change between runs (Python's str hash does)."""
return zlib.crc32(repr(key).encode("utf-8"))
@dataclass
class Stats:
"""Network and load figures of one run."""
tuples_sent: int = 0 # tuples that went to a node other than their home node
messages: int = 0 # nonempty batches between two different nodes
rounds: int = 0 # communication rounds
received: list = field(default_factory=list) # tuples of R and S that each node holds after the shuffle
output: list = field(default_factory=list) # output tuples at each node
def split_round_robin(rel: Relation, p: int) -> list[Relation]:
"""Place the tuples of rel on p nodes in turn, in sorted order (a key-blind placement)."""
parts: list[Counter] = [Counter() for _ in range(p)]
for i, t in enumerate(rel.sorted_rows()):
parts[i % p][t] += 1
return [Relation(rel.schema, c, rel.mode) for c in parts]
def _key(rel: Relation, key: Sequence[str]) -> list[int]:
return [rel.index(a) for a in key]
def _send(t: tuple, c: int, i: int, j: int, inbox: list[Counter], stats: Stats, batches: set) -> None:
"""Move c copies of tuple t from node i to node j and count the network cost."""
inbox[j][t] += c
if j != i:
stats.tuples_sent += c
batches.add((i, j))
def parallel_hash_join(r_parts: Sequence[Relation], s_parts: Sequence[Relation],
key: Sequence[str] | None = None,
h: Callable[[tuple], int] = stable_hash) -> tuple[Relation, Stats]:
"""Join R and S, given as p parts each, by hash redistribution and local hash joins."""
p = len(r_parts)
if p < 1 or len(s_parts) != p:
raise ValueError("R and S need one part on each of the same p >= 1 nodes")
r_schema, s_schema = r_parts[0].schema, s_parts[0].schema
common = [a for a in r_schema if a in s_schema]
key = tuple(common if key is None else key)
if not key or any(a not in common for a in key):
raise ValueError("the routing key must be a nonempty set of common attributes")
rest = [a for a in s_schema if a not in common]
stats = Stats(rounds=1)
batches: set = set()
r_in: list[Counter] = [Counter() for _ in range(p)]
s_in: list[Counter] = [Counter() for _ in range(p)]
rk, sk = _key(r_parts[0], key), _key(s_parts[0], key)
# Redistribution phase: one round in which every node may send to every node.
for i in range(p): # @line L1
for t, c in r_parts[i].rows.items(): # @line L2
_send(t, c, i, h(tuple(t[x] for x in rk)) % p, r_in, stats, batches)
for u, d in s_parts[i].rows.items(): # @line L3
_send(u, d, i, h(tuple(u[x] for x in sk)) % p, s_in, stats, batches)
stats.messages = len(batches)
rc, sc = [r_schema.index(a) for a in common], [s_schema.index(a) for a in common]
rest_pos = [s_schema.index(a) for a in rest]
out: Counter = Counter()
for j in range(p): # @line L4
r_local, s_local = r_in[j], s_in[j] # @line L5
table: dict = {}
for t, c in r_local.items(): # @line L6
k = tuple(t[x] for x in rc)
if None not in k:
table.setdefault(k, []).append((t, c))
made = 0
for u, d in s_local.items(): # @line L7
k = tuple(u[x] for x in sc)
for t, c in table.get(k, ()):
out[t + tuple(u[x] for x in rest_pos)] += c * d
made += c * d
stats.received.append(sum(r_local.values()) + sum(s_local.values()))
stats.output.append(made)
return Relation(r_schema + tuple(rest), out, "bag"), stats # @line L8
def broadcast_join(r_parts: Sequence[Relation], s_parts: Sequence[Relation]) -> tuple[Relation, Stats]:
"""The fragment-and-replicate variant: every node gets all of R and joins it with its own S_i."""
p = len(r_parts)
if p < 1 or len(s_parts) != p:
raise ValueError("R and S need one part on each of the same p >= 1 nodes")
r_schema, s_schema = r_parts[0].schema, s_parts[0].schema
common = [a for a in r_schema if a in s_schema]
rest = [a for a in s_schema if a not in common]
rc, sc = [r_schema.index(a) for a in common], [s_schema.index(a) for a in common]
rest_pos = [s_schema.index(a) for a in rest]
whole: Counter = Counter()
for part in r_parts:
whole.update(part.rows)
stats = Stats(rounds=1)
for i, part in enumerate(r_parts):
size = sum(part.rows.values())
stats.tuples_sent += size * (p - 1)
if size:
stats.messages += p - 1
table: dict = {}
for t, c in whole.items():
k = tuple(t[x] for x in rc)
if None not in k:
table.setdefault(k, []).append((t, c))
out: Counter = Counter()
for j in range(p):
made = 0
for u, d in s_parts[j].rows.items():
for t, c in table.get(tuple(u[x] for x in sc), ()):
out[t + tuple(u[x] for x in rest_pos)] += c * d
made += c * d
stats.received.append(sum(whole.values()) + sum(s_parts[j].rows.values()))
stats.output.append(made)
return Relation(r_schema + tuple(rest), out, "bag"), stats
test_parallel_hash_join.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parallel-hash-join/. The authors are listed in prov/XNDHHS.jsonl.
import random
from collections import Counter
import pytest
import dbrel
from dbrel import Relation
from parallel_hash_join import broadcast_join, parallel_hash_join, split_round_robin, stable_hash
def whole(parts):
c = Counter()
for part in parts:
c.update(part.rows)
return Relation(parts[0].schema, c)
def oracle_sent(r_parts, s_parts, key, h=stable_hash):
"""Count the tuples whose target node differs from their home node, directly."""
p = len(r_parts)
sent = 0
pairs = set()
for parts in (r_parts, s_parts):
for i, part in enumerate(parts):
for t in part.sorted_rows():
j = h(tuple(t[part.index(a)] for a in key)) % p
if j != i:
sent += 1
pairs.add((i, j))
return sent, len(pairs)
def random_parts(rng, schema, n, p, domain, null_rate=0.0):
rel = dbrel.random_relation(rng, schema, n, domain, null_rate=null_rate)
if rng.random() < 0.5:
return split_round_robin(rel, p)
parts = [Counter() for _ in range(p)]
for t in rel.sorted_rows():
parts[rng.randrange(p)][t] += 1
return [Relation(schema, c) for c in parts]
@pytest.mark.parametrize("seed", range(60))
def test_matches_natural_join(seed):
rng = random.Random(seed)
p = rng.randint(1, 8)
r_parts = random_parts(rng, ("A", "B"), rng.randint(0, 40), p, {"A": 5, "B": 3}, 0.1 * (seed % 2))
s_parts = random_parts(rng, ("A", "C"), rng.randint(0, 40), p, {"A": 5, "C": 4}, 0.1 * (seed % 2))
out, stats = parallel_hash_join(r_parts, s_parts)
expect = dbrel.natural_join(whole(r_parts), whole(s_parts))
assert out == expect
assert sum(stats.output) == len(expect)
assert sum(stats.received) == len(whole(r_parts)) + len(whole(s_parts))
sent, msgs = oracle_sent(r_parts, s_parts, ("A",))
assert stats.tuples_sent == sent
assert stats.messages == msgs <= p * (p - 1)
assert stats.rounds == 1
@pytest.mark.parametrize("seed", range(20))
def test_two_key_attributes_and_partial_key(seed):
rng = random.Random(100 + seed)
p = rng.randint(2, 6)
dom = {"A": 3, "B": 3, "C": 4, "D": 4}
r_parts = random_parts(rng, ("A", "B", "C"), rng.randint(0, 30), p, dom)
s_parts = random_parts(rng, ("B", "A", "D"), rng.randint(0, 30), p, dom)
expect = dbrel.natural_join(whole(r_parts), whole(s_parts))
for key in (None, ("A",), ("B",), ("A", "B")):
out, _ = parallel_hash_join(r_parts, s_parts, key)
assert out == expect
def test_hand_cases():
empty_r = [Relation(("A", "B"), []) for _ in range(3)]
empty_s = [Relation(("A", "C"), []) for _ in range(3)]
out, stats = parallel_hash_join(empty_r, empty_s)
assert len(out) == 0 and stats.tuples_sent == 0 and stats.messages == 0
one_r = [Relation(("A", "B"), [(1, "x")])]
one_s = [Relation(("A", "C"), [(1, "y"), (1, "y")])]
out, stats = parallel_hash_join(one_r, one_s)
assert out.rows == Counter({(1, "x", "y"): 2})
assert stats.tuples_sent == 0
nulls_r = [Relation(("A", "B"), [(None, 1), (2, 1)]), Relation(("A", "B"), [(2, 2)])]
nulls_s = [Relation(("A", "C"), [(None, 5)]), Relation(("A", "C"), [(2, 6)])]
out, _ = parallel_hash_join(nulls_r, nulls_s)
assert out.rows == Counter({(2, 1, 6): 1, (2, 2, 6): 1})
def test_skew_sends_everything_to_one_node():
p = 4
r = Relation(("A", "B"), [(7, b) for b in range(12)])
s = Relation(("A", "C"), [(7, c) for c in range(8)])
out, stats = parallel_hash_join(split_round_robin(r, p), split_round_robin(s, p))
assert len(out) == 96
j = stable_hash((7,)) % p
assert stats.received[j] == 20 and sum(stats.received) == 20
assert stats.output[j] == 96
assert stats.tuples_sent == 15 # 3 of 12 and 2 of 8 tuples already sit on node j
def test_co_partitioned_input_sends_nothing():
rng = random.Random(7)
p = 5
r = dbrel.random_relation(rng, ("A", "B"), 50, {"A": 5, "B": 3})
s = dbrel.random_relation(rng, ("A", "C"), 50, {"A": 5, "C": 3})
def by_hash(rel):
parts = [Counter() for _ in range(p)]
for t, c in rel.rows.items():
parts[stable_hash((t[0],)) % p][t] += c
return [Relation(rel.schema, x) for x in parts]
out, stats = parallel_hash_join(by_hash(r), by_hash(s))
assert out == dbrel.natural_join(r, s)
assert stats.tuples_sent == 0 and stats.messages == 0
def test_page_example():
h = lambda k: k[0]
r = [Relation(("A", "B"), [(3, "r0"), (1, "r3"), (2, "r6")]),
Relation(("A", "B"), [(1, "r1"), (5, "r4"), (6, "r7")]),
Relation(("A", "B"), [(4, "r2"), (9, "r5")])]
s = [Relation(("A", "C"), [(1, "s0"), (8, "s3")]),
Relation(("A", "C"), [(4, "s1"), (5, "s4")]),
Relation(("A", "C"), [(1, "s2"), (3, "s5")])]
out, stats = parallel_hash_join(r, s, h=h)
assert out == dbrel.natural_join(whole(r), whole(s))
assert len(out) == 7
assert stats.received == [4, 6, 4]
assert stats.output == [1, 5, 1]
assert stats.tuples_sent == 11
assert stats.messages == 6
@pytest.mark.parametrize("seed", range(20))
def test_broadcast_variant(seed):
rng = random.Random(500 + seed)
p = rng.randint(1, 8)
r_parts = random_parts(rng, ("A", "B"), rng.randint(0, 15), p, {"A": 4, "B": 3})
s_parts = random_parts(rng, ("A", "C"), rng.randint(0, 40), p, {"A": 4, "C": 3})
out, stats = broadcast_join(r_parts, s_parts)
assert out == dbrel.natural_join(whole(r_parts), whole(s_parts))
assert stats.tuples_sent == len(whole(r_parts)) * (p - 1)
def test_bad_arguments():
r = [Relation(("A", "B"), [])]
s = [Relation(("A", "C"), [])]
with pytest.raises(ValueError):
parallel_hash_join(r, s + s)
with pytest.raises(ValueError):
parallel_hash_join(r, s, key=("B",))
History
The GRACE database machine of Kitsuregawa, Tanaka and Moto-oka (1983) split the two relations into buckets by a hash function, so that each pair of buckets could be joined apart from the others and in parallel. DeWitt and Gerber (1985) gave multiprocessor versions of the Grace and Hybrid hash joins, measured them in a simulation, and found close to linear speedup. The Gamma machine of DeWitt et al. ran on 32 processors of an Intel iPSC/2 in 1990. It routed tuples through split tables, which map hash values to nodes, and used the parallel Hybrid hash join as its default join. The same plan returned in MapReduce as the reduce-side join.
References
- David J. DeWitt and Robert H. Gerber, Multiprocessor hash-based join algorithms, Proceedings of the 11th International Conference on Very Large Data Bases (VLDB), 1985, pages 151 to 164, Section 4.2.1 (the multiprocessor Grace hash join with partitioning nodes and joining nodes), Section 4.2.2 (the multiprocessor Hybrid hash join), and Section 4.3.2 (the assumption that the smaller relation fits in the aggregate memory, and bucket overflow)
- Masaru Kitsuregawa, Hidehiko Tanaka and Tohru Moto-oka, Application of hash to data base machine and its architecture, New Generation Computing 1(1), 1983, pages 63 to 74, the GRACE hash join, which partitions both relations into buckets by hashing and joins each pair of buckets separately
- David J. DeWitt, Shahram Ghandeharizadeh, Donovan A. Schneider, Allan Bricker, Hui-I Hsiao and Rick Rasmussen, The Gamma database machine project, IEEE Transactions on Knowledge and Data Engineering 2(1), 1990, pages 44 to 62, the sections on declustering (round robin, hashed and range partitioning), on split tables, and on the join operator (the parallel Hybrid hash join is the default), and the speedup and scaleup measurements of join queries
- M. Tamer Özsu and Patrick Valduriez, Principles of Distributed Database Systems, fourth edition, Springer, 2020, Chapter 8, Parallel Database Systems
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 XNDHHS Edit this page History Report an error Markdown