Techniquecore
Dictionary encoding
Also called order-preserving dictionary encoding, domain encoding.
Replace each value of a column by a small integer code from a dictionary of its distinct values. If the dictionary is sorted, the codes keep the order and range filters run on codes.
Dictionary encoding is the most common compression scheme of column stores, tables kept as in the decomposition storage model. It lists the distinct values of a column once, in a dictionary , and stores the column as a list of small integer codes, each the index of a value in , packed in bits each by bit packing. A column of a million city names with a thousand distinct cities becomes a dictionary of a thousand names and a million 10-bit codes. It is the column form of dictionary-based compression: the dictionary has whole values, not substrings of a text, and every code has the same width, so the code of row is at bit . A scan can evaluate a predicate on the codes without decoding them, which is why the scheme fits late materialization. If is sorted, the dictionary is order-preserving: exactly when , and a range predicate on values becomes a range of codes. If is in order of arrival, only equality is preserved.
In plain words
Think of a long list of city names, one per row, where the same few cities appear again and again. Instead of writing "Paris" a thousand times, write a short list of the cities once, number them, and keep only the numbers in the long list. Numbers are short, so the list becomes much smaller.
To find the rows with Paris, look up the number of Paris once and then search the list of numbers. You never need to read a name again.
If the short list is in alphabetical order, the numbers are in alphabetical order too. Then "cities before Paris" is just "numbers smaller than the number of Paris". If the short list is in the order the cities first came in, the numbers say nothing about order, and you must check each city of the short list by name.
When it applies
- The column has few distinct values compared with its number of rows, for example countries, status flags, product categories or dates. The scheme pays when bits plus the dictionary is much less than the plain column.
- The values are wide, such as strings, so that a code of a few bits replaces many bytes and a comparison of codes replaces a comparison of strings.
- The queries filter, group or join on the column. Equality, grouping and joins need only equal codes for equal values, which every dictionary gives. Range predicates and sorting need an order-preserving dictionary.
- The column is mostly read, or written in batches. A new value either goes at the end of an unordered dictionary or forces a new code assignment in an ordered one.
The template
The column has values , each NULL or a value of one ordered type. A predicate is one of with a constant ; a comparison with NULL is never true.
ENCODE(a, ordered)- 1
D ← the distinct non-null values of a, sorted if ordered, else in order of first appearance - 2
code(D[x]) ← x + 1 for x ← 0 to |D| - 1, and code(NULL) ← 0 - 3
w ← the number of bits of |D|, at least 1 - 4
for i ← 0 to N - 1 do write code(a[i]) in the w bits at bit i·w - 5
CODE(i): read the w bits at bit i·w - 6
DECODE(i): c ← CODE(i); if c = 0 then return NULL else return D[c - 1] SELECT(θ, v)- 7
if the dictionary is ordered and θ is not ≠ then - 8
[s, e) ← the codes of the values x with x θ v, from two binary searches of v in D - 9
return the positions i with s ≤ CODE(i) < e - 10
S ← the empty set - 11
for x ← 0 to |D| - 1 do if D[x] θ v then add x + 1 to S - 12
return the positions i with CODE(i) in S
Code 0 is kept for NULL, so a NULL never falls in a code range or in , and the codes go from 0 to , which fit in bits. The binary searches of line L8 find , the number of entries less than , and , the number of entries at most ; then gives codes , gives , gives , gives and gives . The constant need not be in the dictionary.
Why it works. Codes are distinct for distinct values and the -bit fields do not overlap, so DECODE returns the value that was encoded. In a sorted dictionary, is strictly increasing, so the values that satisfy a range predicate are a contiguous run of , and their codes are an interval. In an unordered dictionary, line L11 tests each value of directly, so holds exactly the codes of the values that pass. In both cases a row passes if and only if its code is chosen, and no value is decoded. The proof file has the details.
Cost. The column takes bytes for the codes plus the dictionary, where . A selection with an ordered dictionary makes comparisons of values, where , and then comparisons of integers. With an unordered dictionary it makes comparisons of values and tests of membership in , which are one bit read each if is a bitmap. Both are , but only or of the steps compare the original values, which may be long strings.
Example. Take the column (Paris, Berlin, Paris, Rome, Berlin, Paris, NULL, Athens), with .
| position | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| value | Paris | Berlin | Paris | Rome | Berlin | Paris | NULL | Athens |
| ordered code | 3 | 2 | 3 | 4 | 2 | 3 | 0 | 1 |
| unordered code | 1 | 2 | 1 | 3 | 2 | 1 | 0 | 4 |
The ordered dictionary is (Athens, Berlin, Paris, Rome); the unordered one is (Paris, Berlin, Rome, Athens). There are 4 values, so and the 8 codes take 24 bits, 3 bytes. For "city < Paris", the ordered dictionary has entries less than Paris, so the code range is and the scan returns positions 1, 4 and 7. For "city >= Oslo", Oslo is not in the dictionary, , and the code range is , the codes of Paris and Rome. The unordered dictionary must compare Paris with all 4 entries, finds that Berlin and Athens pass, and scans for the code set ; it returns the same positions 1, 4 and 7. Note that in the unordered codes Athens has the largest code, 4, so "code < code(Paris)" would give the wrong answer.
Classic examples
- C-Store. Abadi, Madden and Ferreira (2006) put dictionary encoding among the schemes of C-Store and run selections and aggregations directly on the codes. An equality predicate becomes an integer comparison, and a group-by groups on codes and decodes only one value per group.
- Column-store surveys. Abadi, Boncz, Harizopoulos, Idreos and Madden (2013) describe dictionary encoding as a basic scheme of modern column stores, together with run-length encoding and frame of reference encoding, and discuss operating on compressed data.
- Columnar file formats. Parquet and ORC write a dictionary page per column chunk and store the codes with bit packing and run-length encoding, falling back to plain values when the dictionary grows too large.
- Joins and grouping. If two columns share one dictionary, a join on them is a join on codes. A group-by on an encoded column can use the code as an index into an array of aggregates, with no hash table.
Variations
- Order-preserving or not. A sorted dictionary allows range predicates, sorting and min and max on codes, but a new value in the middle of the order forces a re-encoding of the column or a code with gaps. An unordered dictionary appends new values at the end, so it is cheap to update, but only equality, grouping and joins work on the codes.
- Order-preserving with updates. Binnig, Hildenbrand and Faerber (2009) keep the order for string dictionaries that grow, by leaving gaps between codes and by indexing the dictionary for both encoding and decoding.
- Compressed dictionaries. A sorted dictionary of strings can itself be stored with front coding, since neighbor entries share prefixes.
- Local or global dictionaries. A dictionary per block keeps and small and lets a zone map skip blocks, but codes of different blocks cannot be compared. A global dictionary allows joins on codes across the whole table.
- Codes of variable length. Giving frequent values shorter codes, as Huffman coding does, saves more space but loses the fixed width, so the code of row can no longer be found without decoding the rows before it.
Pitfalls
- Range predicates on unordered codes. Comparing codes of an unordered dictionary with gives wrong results, as in the example. The plan must know whether the dictionary is ordered.
- High cardinality. If almost every value is distinct, the dictionary is as large as the column, and the codes add bits. Check against before choosing the scheme, and fall back to plain storage.
- Growing code width. When passes a power of two, grows by one bit and every code must be rewritten. Reserve a width, or start a new block with a new dictionary.
- NULL handling. NULL needs a code of its own, or a separate null bitmap. If NULL gets an ordinary code, a range of codes can include it by mistake.
- Collation. An ordered dictionary of strings is sorted by one collation. A query with another collation, or with case-insensitive comparison, cannot use the code order.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# 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)
dictionary_encoding.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dictionary-encoding/. The authors are listed in prov/4407VK.jsonl.
"""Dictionary encoding of one column, with and without order preservation.
The dictionary D lists the distinct non-null values of the column. Value D[x]
has the code x + 1, and NULL has the code 0. In an ordered dictionary D is
sorted, so that a < b if and only if code(a) < code(b); in an unordered one D
is in order of first appearance. The codes are packed, w bits each, into a
bytearray, least significant bit first, where w is the number of bits of |D|.
A selection with a comparison (=, <>, <, <=, >, >=) and a constant returns the
positions where it holds; a comparison with NULL never holds. An ordered
dictionary turns a range predicate into a range of codes with two binary
searches. An unordered one must compare the constant with every entry of D.
The counters self.compares and self.decodes count comparisons of values and
lookups of D, so that tests can check that a scan works on codes only.
"""
import bisect
import operator
from typing import Dict, List, Optional, Sequence, Set
OPS = {"=": operator.eq, "<>": operator.ne, "<": operator.lt,
"<=": operator.le, ">": operator.gt, ">=": operator.ge}
class DictColumn:
def __init__(self, values: Sequence[object], ordered: bool = True) -> None:
self.ordered = ordered
distinct = list(dict.fromkeys(v for v in values if v is not None))
self.D: List[object] = sorted(distinct) if ordered else distinct # @line L1
self.code: Dict[object, int] = {v: x + 1 for x, v in enumerate(self.D)} # @line L2
self.w = max(1, len(self.D).bit_length()) # @line L3
self.n = len(values)
self.bits = bytearray((self.n * self.w + 7) // 8)
for i, v in enumerate(values): # @line L4
self._put(i, 0 if v is None else self.code[v]) # @line L2 L4
self.compares = 0
self.decodes = 0
# ------------------------------------------------------------ bits
def _put(self, i: int, x: int) -> None:
pos = i * self.w
for b in range(self.w):
if x >> b & 1:
self.bits[(pos + b) >> 3] |= 1 << ((pos + b) & 7)
def code_at(self, i: int) -> int:
pos, x = i * self.w, 0 # @line L5
for b in range(self.w): # @line L5
x |= (self.bits[(pos + b) >> 3] >> ((pos + b) & 7) & 1) << b # @line L5
return x
def size_bytes(self) -> int:
return len(self.bits)
# ------------------------------------------------------------ decode
def decode(self, i: int) -> object:
x = self.code_at(i)
if x == 0: # @line L6
return None # @line L6
self.decodes += 1
return self.D[x - 1] # @line L6
def decode_all(self) -> List[object]:
return [self.decode(i) for i in range(self.n)]
# ------------------------------------------------------------ select
def code_range(self, op: str, v: object) -> Optional[range]:
"""For an ordered dictionary: the codes whose values satisfy op v, as a range."""
lo = bisect.bisect_left(self.D, v) # first entry >= v
hi = bisect.bisect_right(self.D, v) # first entry > v
self.compares += 2 * max(1, len(self.D)).bit_length()
first, last = {"=": (lo, hi), "<": (0, lo), "<=": (0, hi),
">": (hi, len(self.D)), ">=": (lo, len(self.D))}[op]
return range(first + 1, last + 1)
def matching_codes(self, op: str, v: object) -> Set[int]:
"""For any dictionary: the codes whose values satisfy op v, by |D| comparisons."""
self.compares += len(self.D)
return {x + 1 for x, d in enumerate(self.D) if OPS[op](d, v)}
def select(self, op: str, v: object) -> List[int]:
if op not in OPS:
raise ValueError(f"unknown comparison {op}")
if v is None:
return []
if self.ordered and op != "<>": # @line L7
r = self.code_range(op, v) # @line L8
return [i for i in range(self.n) if r.start <= self.code_at(i) < r.stop] # @line L9
if op == "<>" and v in self.code: # the complement of one code
c = self.code[v]
return [i for i in range(self.n) if self.code_at(i) not in (0, c)]
S = self.matching_codes(op, v) # @line L10 L11
return [i for i in range(self.n) if self.code_at(i) in S] # @line L12
test_dictionary_encoding.py 85 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dictionary-encoding/. The authors are listed in prov/4407VK.jsonl.
import random
import unittest
import dbrel
from dictionary_encoding import DictColumn
CITIES = ["Paris", "Berlin", "Paris", "Rome", "Berlin", "Paris", None, "Athens"]
OPS = ["=", "<>", "<", "<=", ">", ">="]
def expected_positions(values, op, v):
rel = dbrel.Relation(("pos", "v"), list(enumerate(values)))
sel = dbrel.select(rel, lambda row: dbrel.cmp3(op, row["v"], v))
return sorted(p for p, _ in sel.rows)
class TestDictionaryEncoding(unittest.TestCase):
def test_worked_example(self):
col = DictColumn(CITIES, ordered=True)
self.assertEqual(col.D, ["Athens", "Berlin", "Paris", "Rome"])
self.assertEqual(col.w, 3)
self.assertEqual([col.code_at(i) for i in range(8)], [3, 2, 3, 4, 2, 3, 0, 1])
self.assertEqual(col.size_bytes(), 3)
self.assertEqual(col.code_range("<", "Paris"), range(1, 3))
self.assertEqual(col.select("<", "Paris"), [1, 4, 7])
self.assertEqual(col.code_range(">=", "Oslo"), range(3, 5))
self.assertEqual(col.decodes, 0)
self.assertEqual(col.decode_all(), CITIES)
un = DictColumn(CITIES, ordered=False)
self.assertEqual(un.D, ["Paris", "Berlin", "Rome", "Athens"])
self.assertEqual([un.code_at(i) for i in range(8)], [1, 2, 1, 3, 2, 1, 0, 4])
self.assertEqual(un.matching_codes("<", "Paris"), {2, 4})
self.assertEqual(un.select("<", "Paris"), [1, 4, 7])
self.assertEqual(un.compares, 8)
self.assertEqual(un.decodes, 0)
def test_round_trip_and_size(self):
for seed in range(100):
rng = random.Random(seed)
n = rng.randrange(0, 300)
d = rng.choice([1, 2, 3, 7, 8, 100, 1000])
pool = [rng.randrange(-10 ** 6, 10 ** 6) for _ in range(d)]
if rng.random() < 0.5:
pool = [str(x) for x in pool]
values = [None if rng.random() < 0.1 else rng.choice(pool) for _ in range(n)]
for ordered in (True, False):
col = DictColumn(values, ordered)
self.assertEqual(col.decode_all(), values)
distinct = len(set(v for v in values if v is not None))
self.assertEqual(len(col.D), distinct)
self.assertEqual(col.w, max(1, distinct.bit_length()))
self.assertEqual(col.size_bytes(), (n * col.w + 7) // 8)
def test_order_preservation(self):
rng = random.Random(7)
values = [rng.choice("abcdefghij") * rng.randrange(1, 3) for _ in range(200)]
col = DictColumn(values, ordered=True)
for i in range(0, 200, 7):
for j in range(0, 200, 11):
self.assertEqual(values[i] < values[j], col.code_at(i) < col.code_at(j))
def test_selections_against_dbrel(self):
for seed in range(150):
rng = random.Random(500 + seed)
n = rng.randrange(0, 80)
values = [None if rng.random() < 0.15 else rng.randrange(20) for _ in range(n)]
for ordered in (True, False):
col = DictColumn(values, ordered)
for _ in range(5):
op, v = rng.choice(OPS), rng.choice([None] + list(range(-2, 23)))
self.assertEqual(col.select(op, v), expected_positions(values, op, v),
(ordered, op, v))
self.assertEqual(col.decodes, 0)
def test_unknown_operator(self):
with self.assertRaises(ValueError):
DictColumn([1, 2]).select("~", 1)
if __name__ == "__main__":
unittest.main()
Exercises
- A column has rows and 3,000 distinct strings of 12 bytes on average. Compute the size of the plain column and of the dictionary-encoded column, with the dictionary.
- Show how to evaluate "v BETWEEN x AND y" on an ordered dictionary with two binary searches, and how to evaluate "v LIKE 'Ber%'" as a code range.
- An unordered dictionary receives values in arbitrary order. Give an algorithm that turns it into an ordered dictionary and rewrites the codes, and give its cost in terms of and .
- Prove that a group-by on an encoded column with an array of counters gives the same groups as a group-by on the values, with NULL as one group.
Proof: Dictionary encoding decodes every value back, keeps the order when the dictionary is sorted, and answers selections on codes alonefull
We use the notation of the page. A column is a list of values, each of them NULL or an element of a set on which is a total order. The dictionary lists the distinct non-null values once each (line L1), and (line L2), and is the number of bits of , at least 1 (line L3). A comparison with NULL is never true.
Lemma 1 (codes fit). The map code is a bijection from the values of the column, with NULL, to , and every code fits in bits.
Proof. The entries of are distinct, so is a bijection from to the non-null values, and maps it to . NULL alone has code 0. If the only code is 0 and . Otherwise has bits, so , and every code is at most .
Lemma 2 (round trip). For every , code_at(i) returns , and decode(i) returns .
Proof. Line L4 writes the bits of at the bit positions to . For these ranges are disjoint, and the array starts with all bits 0, so writing one code does not change another, and the bits of code are exactly the bits of , which fit by Lemma 1. Line L5 reads the same positions in the same order of significance. Line L6 maps 0 to NULL and to , the inverse of the map of line L2.
The array has bytes.
Lemma 3 (order). If the dictionary is ordered, then for non-null values and of the column, if and only if , and if and only if the codes are equal.
Proof. In the ordered case line L1 sorts the distinct values, so is strictly increasing: if and only if . Add 1 to both sides. Equality follows from Lemma 1.
If the dictionary is in order of first appearance, Lemma 3 fails in general: in the example of the page, Paris has code 1 and Athens has code 4.
Theorem 1 (selection). For a comparison in and a constant , SELECT returns, in increasing order, exactly the positions with not NULL and true. It reads no entry of at those positions.
Proof. If is NULL no comparison is true, and SELECT returns the empty list. Otherwise let be the number of entries of that are less than and the number that are at most . These are the results of the two binary searches of line L8, and they are correct because is sorted in the ordered case. Since is strictly increasing, the indices with form an interval:
| indices |
The code range of line L8 is this interval shifted by 1. Its smallest possible code is 1, so the NULL code 0 is never in it. By Lemma 2, line L9 keeps position if and only if is in the range, that is, if and only if is not NULL and . Note that need not be in .
In the other case (an unordered dictionary, or is ), lines L10 and L11 compare with each entry and put in exactly when . The code 0 is never put in . By Lemma 2, line L12 keeps if and only if is not NULL and . When is and is in , the implementation skips the loop and keeps the codes other than 0 and ; by Lemma 1 these are the codes of the non-null values different from , so the result is the same.
Every branch visits the positions in increasing order and reads only codes, and the dictionary only at lines L8 and L11, never at a position.
Theorem 2 (cost). The ordered branch makes comparisons of values and reads codes. The unordered branch makes comparisons of values and reads codes, each with a test of membership in .
Proof. A binary search in a sorted list of entries makes at most comparisons, and line L8 makes two of them. Line L11 makes one comparison for each entry of . Lines L9 and L12 read each code once.
If is held as a bitmap of bits, each membership test is one bit read, so both branches take steps after the dictionary work, and only the comparisons of the values, which may be long strings, differ.
References
- Integrating compression and execution in column-oriented database systems, the dictionary scheme among the compression methods of C-Store, and the operators that work on the codes
- The design and implementation of modern column-oriented database systems, the section on compression in column stores and the section on operating directly on compressed data
- Dictionary-based order-preserving string compression for main memory column stores, order-preserving dictionaries that accept new values without a full re-encoding
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 | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 4407VK Edit this page History Report an error Markdown