Algorithm Search⌘K

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.

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
Origin
Masaru Kitsuregawa, Hidehiko Tanaka, Tohru Moto oka, David J. DeWitt, Robert H. Gerber, 1983

The parallel hash join computes the equi-join R⋈SR \bowtie S on a shared-nothing machine of pp 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 RR and SS, spread over pp nodes: node ii holds the parts RiR_i and SiS_i, and RR is the bag union of the RiR_i. The output is the natural join R⋈SR \bowtie S under bag semantics, as on the relational join problem: if a tuple rr of RR matches a tuple ss of SS on the common attributes JJ, the output holds r⋅sr \cdot s once for each pair of copies, and a NULL in JJ matches nothing. A routing key KK is a nonempty subset of JJ, often all of JJ. 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 n=∣R∣+∣S∣n = |R| + |S| for the number of input tuples and zz for the number of output tuples. In the BSP model, the redistribution is one superstep whose hh-relation is the largest number of tuples that one node sends or receives.

The algorithm

  1. PARALLEL-HASH-JOIN(R_0..R_{p-1}, S_0..S_{p-1}, K, h) ▷ node i holds R_i and S_i
  2. 1for each node i = 0, ..., p - 1 do in parallel ▷ redistribution, one round
  3. 2for each tuple r of R_i do send r to node h(r[K]) mod p
  4. 3for each tuple s of S_i do send s to node h(s[K]) mod p
  5. 4for each node j = 0, ..., p - 1 do in parallel ▷ local join phase
  6. 5R'_j, S'_j ← the tuples of R and of S that node j received
  7. 6build a hash table on R'_j with the key r[J]
  8. 7for 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
  9. 8return 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 Rj′R'_j does not fit in the memory of node jj, the node runs a Grace or hybrid hash join instead; this changes the local disk cost, not the network cost.

The function hh 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 hh: every key at node jj has the same value of hh modulo pp, so a table indexed by hh modulo a multiple of pp would use only a fraction of its buckets.

Example

Let p=3p = 3 and h(v)=vh(v) = v, so the target of key vv is v mod 3v \bmod 3. R(A,B)R(A, B) has the tuples r0r_0 to r7r_7 with the keys 3,1,4,1,5,9,2,63, 1, 4, 1, 5, 9, 2, 6, and S(A,C)S(A, C) has the tuples s0s_0 to s5s_5 with the keys 1,4,1,8,5,31, 4, 1, 8, 5, 3. The tuples start in round robin order: tuple number kk is at node k mod 3k \bmod 3.

node holds at the start receives in lines L1 to L3 local output
0 r0r_0 (3), r3r_3 (1), r6r_6 (2); s0s_0 (1), s3s_3 (8) r0,r5,r7r_0, r_5, r_7; s5s_5 r0s5r_0 s_5: 1 tuple
1 r1r_1 (1), r4r_4 (5), r7r_7 (6); s1s_1 (4), s4s_4 (5) r1,r2,r3r_1, r_2, r_3; s0,s1,s2s_0, s_1, s_2 key 1: 2×2=42 \times 2 = 4, key 4: 1; 5 tuples
2 r2r_2 (4), r5r_5 (9); s2s_2 (1), s5s_5 (3) r4,r6r_4, r_6; s3,s4s_3, s_4 r4s4r_4 s_4: 1 tuple

Only r0r_0, r1r_1 and s1s_1 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 R⋈SR \bowtie S. For comparison, a broadcast of RR to the two other nodes sends 16 tuples, and a broadcast of SS sends 12.

Skew changes the picture. Take p=4p = 4, 12 tuples of RR and 8 tuples of SS, all with the key 7, placed round robin. Every tuple goes to node h(7) mod 4h(7) \bmod 4. 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 JJ, so they agree on K⊆JK \subseteq J, have the same value of hh, 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. RR is the bag union of its parts R0,…,Rp−1R_0, \dots, R_{p-1}, and SS is the bag union of S0,…,Sp−1S_0, \dots, S_{p-1}. The routing key KK is a nonempty set of attributes that RR and SS have in common, and JJ is the set of all common attributes, so K⊆JK \subseteq J. The output R⋈SR \bowtie S is the bag in which the tuple r⋅sr \cdot s (the tuple rr extended by the attributes of ss outside JJ) has as many copies as there are pairs of occurrences (r,s)(r, s) with r[J]=s[J]r[J] = s[J] and no NULL in r[J]r[J]. We treat each stored copy of a tuple as a distinct occurrence. The hash function hh 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 RR and of SS is at exactly one node. An occurrence rr is at node h(r[K]) mod ph(r[K]) \bmod p, and an occurrence ss is at node h(s[K]) mod ph(s[K]) \bmod p.

Proof. Lines L1 and L2 visit each node ii once and each occurrence of RiR_i once, and send it to one node. The parts RiR_i together hold each occurrence of RR exactly once, so each occurrence of RR is sent once. Nothing is sent twice or dropped, because the simulation does not lose messages. The same holds for SS by line L3. The target node is the value that the line computes. □\square

Lemma 2 (co-location). If r[J]=s[J]r[J] = s[J], then rr and ss are at the same node after line L3.

Proof. K⊆JK \subseteq J, so r[J]=s[J]r[J] = s[J] gives r[K]=s[K]r[K] = s[K]. Then h(r[K]) mod p=h(s[K]) mod ph(r[K]) \bmod p = h(s[K]) \bmod p, because hh is a function. By Lemma 1 both occurrences are at that node. □\square

Theorem 1 (correctness). The bag that line L8 returns is R⋈SR \bowtie S.

Proof. Fix a node jj, and let Rj′R'_j and Sj′S'_j be the occurrences that it holds after line L3. Lines L6 and L7 are the hash join of the page hash join on Rj′R'_j and Sj′S'_j with the key JJ: line L6 puts each occurrence of Rj′R'_j whose key has no NULL into the bucket of its key, once, and line L7 meets each occurrence ss of Sj′S'_j once and outputs r⋅sr \cdot s for each occurrence rr in the bucket of s[J]s[J]. A NULL in s[J]s[J] finds no bucket, because no key in the table has a NULL. So node jj outputs one copy of r⋅sr \cdot s for each pair (r,s)(r, s) in Rj′×Sj′R'_j \times S'_j with r[J]=s[J]r[J] = s[J] and no NULL in r[J]r[J]. This is the bag Rj′⋈Sj′R'_j \bowtie S'_j.

Now take any matching pair (r,s)(r, s) of R×SR \times S. By Lemma 2, both are at one node jj, so the pair appears in Rj′⋈Sj′R'_j \bowtie S'_j. 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 r⋅sr \cdot s for each matching pair. That is R⋈SR \bowtie S. □\square

Theorem 2 (termination). The algorithm stops after O(n+z)O(n + z) steps of work in total, where n=∣R∣+∣S∣n = |R| + |S| counts occurrences and z=∣R⋈S∣z = |R \bowtie S|, if each insert and each lookup of a bucket takes O(1)O(1) steps plus the length of the bucket that it scans.

Proof. Lines L1 to L3 do one send per occurrence: nn sends. Line L6 does ∣Rj′∣|R'_j| inserts at node jj, and these add up to ∣R∣|R| over all nodes by Lemma 1. Line L7 does ∣Sj′∣|S'_j| lookups, which add up to ∣S∣|S|. The work of the lookups beyond O(1)O(1) each is the number of matching pairs they output, which adds up to zz 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. □\square

Theorem 3 (network cost). The algorithm uses one round of communication. It sends exactly the occurrences tt of RR and SS whose home node ii differs from h(t[K]) mod ph(t[K]) \bmod p, so at most nn tuples, and at most p(p−1)p(p - 1) messages if the tuples from node ii to node jj 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 (i,j)(i, j) with i≠ji \ne j that carry at least one tuple, and there are p(p−1)p(p - 1) such pairs. □\square

Theorem 4 (expected balance). Suppose that hh maps the distinct key values to nodes independently and uniformly at random, and that the placement of the parts does not depend on hh. Then each node holds n/pn/p 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 n(p−1)/pn(p - 1)/p.

Proof. An occurrence goes to node jj with probability 1/p1/p, so by linearity of expectation node jj receives n/pn/p occurrences in expectation. An occurrence stays at home when its target equals its home node, which happens with probability 1/p1/p under the second assumption. So it is sent with probability (p−1)/p(p - 1)/p, and the expected number of sent tuples is n(p−1)/pn(p - 1)/p. □\square

Theorem 5 (skew bound). Let vv be a value of KK, and let mRm_R and mSm_S be the numbers of occurrences of RR and SS with key vv. Whatever hh is, one node holds at least mR+mSm_R + m_S occurrences after line L3, and if the tuples with key vv also agree on JJ, that node outputs at least mRmSm_R m_S tuples.

Proof. All these occurrences have the same value vv of KK, so by Lemma 1 they go to the same node h(v) mod ph(v) \bmod p. If they also agree on JJ, every pair of an RR occurrence and an SS occurrence among them matches, and by the proof of Theorem 1 the node outputs each such pair. □\square

Theorem 4 says that the expected load is balanced. It does not bound the largest load. Theorem 5 shows that no choice of hh helps when one key value is frequent: the time of the slowest node is at least proportional to mR+mSm_R + m_S, so with mR+mS≥n/2m_R + m_S \ge n/2 the speed-up over one node is at most about 2, whatever pp is.

Complexity

  • Network (theorem). Each tuple is sent at most once, so at most nn tuples cross the network, in one round and at most p(p−1)p(p - 1) messages. If hh 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 1/p1/p, and the expected number of tuples sent is n(p−1)/pn(p - 1)/p. If both inputs are already hash-partitioned on KK with the same hh, nothing is sent.
  • Local work. Node jj does O(∣Rj′∣+∣Sj′∣+zj)O(|R'_j| + |S'_j| + z_j) expected work, where zjz_j is its output. The join ends when the slowest node ends, so the time is O(n/p+L+D)O(n/p + L + D), where n/pn/p is the scan of the local parts (when they start even), LL the largest load after the shuffle and DD the largest local output.
  • Balance (theorem and its limit). Under a uniform random hh, each node receives n/pn/p tuples in expectation. When every key value has few tuples, the largest load is close to n/pn/p with high probability, by a Chernoff bound. But if one key value has mRm_R tuples in RR and mSm_S in SS, one node receives all mR+mSm_R + m_S of them and outputs mRmSm_R m_S tuples, whatever hh is. See data skew.
  • Memory. In total O(n)O(n) for the inputs; node jj needs room for the hash table on Rj′R'_j.

Properties

  • One round. The algorithm talks once. Later nodes do not wait on one another, so the method scales with pp 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 RR, 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 hh sends to it. Uniform hh 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 Rj′R'_j to the nodes of SS before the probe, so that tuples of SS 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 RR is small, send all of RR to every node and leave SS where it is. The cost is ∣R∣(p−1)|R|(p - 1) tuples, and skew in SS 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 ∣R∣(p−1)|R|(p - 1) for a broadcast with about n(p−1)/pn(p - 1)/p 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 hh and the same pp 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. KK must be a subset of the join attributes JJ. If KK holds an attribute outside JJ, two matching tuples can go to different nodes.
  • The same hash for routing and for the local table. All keys at node jj have the same h(v) mod ph(v) \bmod p. A local table indexed by h(v) mod mh(v) \bmod m with mm a multiple of pp 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.

dbrel.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of communication.expected
  • a full proof of communication.worst
  • a full proof of messages.worst
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example