Algorithmadvanced
HRU greedy view selection
Also called Harinarayan-Rajaraman-Ullman algorithm, greedy cube materialization.
Choose views of a data cube lattice one at a time by largest benefit. The greedy benefit is at least (e - 1)/e, about 63 percent, of the optimal benefit, for a fixed number k of views.
- Solves
- View selection problem
- Time
- O(k n^2) worst
- Space
- O(n^2) extra
- Where
- k = the number of views to choose; n = the number of views in the lattice
- Model
- Word RAM
- Properties
- deterministicnot exactgreedyiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Venky Harinarayan, Anand Rajaraman, Jeffrey D. Ullman, 1996
The HRU greedy algorithm chooses which views of a data cube to store. Harinarayan, Rajaraman and Ullman gave it in 1996. The possible GROUP BY views form a lattice: a view can answer every view that groups by fewer attributes. A query costs the size of the smallest stored view that can answer it. The algorithm stores the top view, then adds more views. Each time it takes the view that lowers the total cost the most. The greedy benefit is at least times the optimal benefit, and this is more than . The view selection page states the general problem, its budgets and its relation to index selection. This page holds the algorithm itself, the full proof of both bounds of the paper, the examples of the paper, and code.
In plain words
A sales table can be summed by part, by supplier, by customer, or by any group of these. Each of these summaries is a view, and a summary by more columns can produce a summary by fewer columns. The full table can produce all of them. If a summary is not stored, a question about it reads the smallest stored summary that can produce it.
The algorithm starts with only the full table stored. In each round, it looks at each summary that is not stored. It adds up how much work that summary would save, over all the questions it could answer. It stores the one that saves the most, and repeats. Each choice is good now but may not be best for all rounds. Even so, the total saving is always at least about 63 percent of the best possible saving with the same number of summaries.
The problem
The input is a set of views with a top view , a relation (view can be answered from view ), a size for each view, and a number . In the cube on attribute set , the views are the subsets of , means , and . In the linear cost model of the paper, answering from a stored set costs
the number of rows of the smallest stored view that can answer it. The top view is always stored. The goal is a set of views besides that minimizes , or with query frequencies , . The paper shows that this problem is NP-complete even in this simple model, by a reduction from set cover.
The algorithm
The benefit of a view for the current set is the drop in total cost when is added:
GREEDY(views V with top t, sizes |v|, weights q_w, number k)- 1
S ← {t} - 2
for i ← 1 to k do - 3
for each view v not in S, compute B(v, S) = the sum over w ⪯ v of q_w · max(0, C_S(w) - |v|) - 4
choose a view v not in S with the largest B(v, S) - 5
S ← S ∪ {v} - 6
return S - {t}, in the order of choice
The code keeps for every view and lowers it after each choice, so line L3 never recomputes the minimum over . For a space limit instead of a count, the variant picks the view with the largest in line L4.
Example
This is Example 4.1 of the paper. The lattice has eight views with these sizes: (the top), , , , , , , . View answers and ; answers and ; answers and ; answers ; answers and ; answers ; and the relation is transitive. With only stored, each of the eight views costs 100, a total of 800. Take .
| view | round 1 | round 2 | round 3 |
|---|---|---|---|
| b | 250 | ||
| c | 125 | 50 | 25 |
| d | 160 | 60 | 60 |
| e | 210 | 60 | 50 |
| f | 120 | 70 | |
| g | 99 | 49 | 49 |
| h | 90 | 40 | 30 |
In round 1, improves itself and the four views below it (, , , ) from 100 to 50 each, a benefit of 250. In round 2, lowers its own cost from 100 to 40 and the cost of from 50 (through ) to 40, a benefit of . In round 3, improves itself and from 50 to 20, a benefit of 60. The greedy choice is , and , with benefit and total cost 420. A search over all 35 sets of three views shows that 380 is the best possible, so greedy is optimal here.
Greedy is not always optimal. In Example 4.2 of the paper, the top view has size 200, and three views , and below it have sizes 100, 99 and 100. Four chains of 20 views of size 100 hang below them: answers chains 1 and 2, chains 2 and 3, chains 3 and 4. With , greedy first takes , with benefit , and then or , with benefit 2100, for a total of 6241. The set has benefit . The ratio is about 0.761, close to the bound for .
Correctness
The proof file proves both results of the paper. The core fact is that the total benefit of a set of views is a monotone submodular function: adding other views can only lower , so it can only lower the benefit of a view. Then the argument of Nemhauser, Wolsey and Fisher applies. If is an optimal set of views and the greedy set after rounds, the views of together add at most times the best single benefit, so the gap to the optimum shrinks by a factor of at least in each round. After rounds the gap is at most of the optimum.
Theorem 1 (Theorem 4.1 of the paper). With views, , and the bound is tight. For it is , and it decreases toward as grows.
Theorem 2 (Theorem 4.2 of the paper, as proved here). If greedy picks by benefit per unit space and has used space , its benefit is at least of the best benefit of any set of views with total size at most . The same proof works with any query weights.
Proof: The HRU greedy algorithm gets at least 1 - (1 - 1/k)^k of the best benefit of k views, and greedy by benefit per unit space gets at least 1 - 1/e of the best benefit in the space it usesfull
Setting. A finite set of views has a top view and a relation (" can be answered from "), which is reflexive, transitive, and has for every . Each view has a size and each query a weight (1 in the plain model). For a set of views with , the cost of is , which exists because . The total cost is . For a set of views, the benefit is . The benefit of a view for is
Line L3 computes this value, and lines L4 and L5 add a view with the largest one.
Lemma 1 (benefit is the gain). For , .
Proof. Adding changes only the costs of the views , and for such the new cost is . The drop is , and the total drop is the weighted sum of these.
So, for , , and the sum of the gains that line L4 records is the benefit of the chosen set.
Lemma 2 (monotone and submodular). If , then for every , for every , and is monotone.
Proof. A minimum over a larger set is not larger. Each term is a nondecreasing function of , so the benefit cannot grow when grows. Monotonicity follows from Lemma 1, because each benefit is at least 0.
Lemma 2 says that is a monotone submodular function: the gain of a view never grows when other views are added.
Lemma 3 (gain of a set). For and any set of views, .
Proof. Add the views of one at a time, . By Lemma 1, the drop in step is , which is at most by Lemma 2. Sum over .
Theorem 1 (fixed number of views). Let the greedy algorithm choose views with total benefit , and let be the largest benefit of any views. Then .
Proof. Let be an optimal set of views, the set after choices, the benefit of choice , and . Every view of is either in , where its benefit for is 0, or a candidate of line L4, whose benefit is at most . By monotonicity and Lemma 3,
So , that is, . With , this gives and . Finally for , so .
If fewer than views besides exist, the greedy algorithm stores them all and is optimal. For the bound is 1: the first choice is the best single view.
Tightness for . In Example 4.2 of the paper, the top view has size 200, three views , and below it have sizes 100, 99 and 100, and four chains of 20 views of size 100 hang below them: answers chains 1 and 2, chains 2 and 3, and chains 3 and 4. Greedy first takes , with benefit , and then or , with benefit , so . The set improves 82 views by 100 each, so , and the ratio is about 0.761. With the size of closer to 100 and chains of views, the ratio is .
Theorem 2 (benefit per unit space). Run greedy with the rule "add the view with the largest " and stop at any step. Let be the chosen views, their space, and the largest benefit of any set of views of total size at most . Then .
Proof. Let be a set of size at most with benefit , and ; if there is nothing to prove, so . Let be the chosen views with sizes and gains , the first of them, and . Each view has , because has the largest ratio, or because the benefit of is 0. By Lemma 3,
so , that is, . If some , then , and stays at most 0 because is monotone. Otherwise every factor is in , and with ,
because . So .
This is the form of the second theorem of Harinarayan, Rajaraman and Ullman: the comparison is with the best use of the space that greedy actually used. Against a fixed limit the bound does not hold if greedy skips a view that does not fit. With a view of size 1 and benefit 2 and a view of size and benefit , greedy takes the small view first and then has no room, so it gets 2 while the best choice gets .
Work. Precompute, for each view, the set of views below it; with views this takes space. Keep for every . Line L3 then costs per view and per round, and the update after line L5 costs . With rounds the time is . For the cube on dimensions, and the views below the view on a set are the subsets of , so a round costs .
Complexity
Let be the number of views. The sets of views below each view take space. Line L3 costs per view, so per round, and the update of after line L5 costs . The total is time. For the cube on attributes, and the view on a set has views below it, so one round costs steps. The sizes of the views are inputs; in practice they are estimated, for example by sampling or by a sketch for the number of distinct groups, which can cost more than the greedy search.
Properties
- Approximation, proved. At least of the optimal benefit, for every lattice and every . This is about the benefit (the saving over storing only the top view), not about the total cost.
- Tight. The paper shows lattices with ratio arbitrarily close to the bound; for , close to .
- Exact for . The first choice is the best single view.
- Nonincreasing gains. By submodularity, each round gains no more than the round before.
- Deterministic. With a fixed tie rule, the same input gives the same choice.
Variants and improvements
- Query frequencies. With a weight per query, the benefit sums , and the bound stays the same (Section 4.5 of the paper).
- Space limit. Pick by benefit per unit space. The bound holds against the best use of the space that greedy has used. Against a fixed limit, a view that does not fit can make plain greedy arbitrarily bad, so a practical version also compares with the best single view that fits.
- Views and indexes. Gupta, Harinarayan, Rajaraman and Ullman (1997) extended the greedy method to choose indexes on the views together with the views.
- AND-OR view graphs. Gupta (1997) generalized the lattice to graphs in which a view can be computed from several others, with greedy algorithms that keep a guarantee.
- Maintenance cost. When the budget is the time to maintain the views, the constraint is not a count or a space limit, and the proofs of this page do not carry over.
When to use it
Use it to choose which aggregates of a star schema or a data cube to precompute, when query costs are roughly proportional to the size of the view read. It is easy to implement, and the guarantee holds for any sizes. When the cost model has indexes, joins or maintenance costs, use it as a heuristic inside a cost-based tool that uses the optimizer's estimates, as in index selection.
Pitfalls
- Reading the bound as a bound on the cost. The 63 percent is about the benefit, the saving over the top view alone. When the best saving is small compared with the cost of the top view, 63 percent of it says little about the total cost.
- Forgetting the top view. The top view must always be stored, or some queries cannot be answered. It is not one of the views.
- Stale costs. After each choice, must be lowered for every view below the new view. Using the costs of the first round makes greedy pick overlapping views, such as and in the example.
- Bad size estimates. The algorithm is only as good as the sizes. The size of a view grouped by several attributes is often much smaller than the product of the numbers of values, and estimating it is a distinct values problem.
- A fixed space limit. See the variant above: picking by benefit per unit space and skipping what does not fit has no guarantee.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hru-greedy-view-selection/. The authors are listed in prov/TY6PHM.jsonl.
"""The greedy view selection algorithm of Harinarayan, Rajaraman and Ullman (SIGMOD 1996).
A lattice of views has a top view, which is always stored, and a relation
"w can be answered from v" (w <= v). In the linear cost model, the cost of
answering w from a set S of stored views is the size of the smallest view
in S that w can be answered from. The benefit of a view v for S is
B(v, S) = sum over w <= v of max(0, C_S(w) - |v|),
the total saving when v is added to S. The greedy algorithm adds, k times,
the view with the largest benefit. Each query w can have a weight (its
frequency); the default weight is 1.
`greedy_views` is the algorithm of the paper. `greedy_per_space` picks by
benefit per unit of space, the variant for a space limit.
"""
from itertools import combinations
from typing import Dict, Hashable, Iterable, List, Optional, Sequence, Set, Tuple
View = Hashable
class Lattice:
"""Views with sizes, the top view, and for each view the views below it."""
def __init__(self, sizes: Dict[View, float], edges: Iterable[Tuple[View, View]],
top: View, weights: Optional[Dict[View, float]] = None):
"""`edges` holds pairs (v, w) where w can be answered from v directly."""
self.size = dict(sizes)
self.top = top
self.views: List[View] = sorted(self.size, key=repr)
children: Dict[View, List[View]] = {v: [] for v in self.views}
for v, w in edges:
if v not in self.size or w not in self.size:
raise ValueError("an edge names an unknown view")
children[v].append(w)
self.below: Dict[View, Set[View]] = {}
for v in self.views:
seen = {v}
stack = [v]
while stack:
for w in children[stack.pop()]:
if w not in seen:
seen.add(w)
stack.append(w)
self.below[v] = seen
if self.below[top] != set(self.views):
raise ValueError("every view must be answerable from the top view")
self.weight = {v: 1 for v in self.views}
if weights:
self.weight.update(weights)
def costs(self, stored: Iterable[View]) -> Dict[View, float]:
"""C_S(w) for every view w: the smallest stored view that answers w."""
stored = set(stored) | {self.top}
cost = {}
for w in self.views:
cost[w] = min(self.size[u] for u in stored if w in self.below[u])
return cost
def total_cost(self, stored: Iterable[View]) -> float:
cost = self.costs(stored)
return sum(self.weight[w] * cost[w] for w in self.views)
def benefit_of_set(self, stored: Iterable[View]) -> float:
"""The saving of a set over storing the top view alone."""
return self.total_cost([]) - self.total_cost(stored)
def _benefit(lat: Lattice, cost: Dict[View, float], v: View) -> float:
s = lat.size[v]
return sum(lat.weight[w] * (cost[w] - s) for w in lat.below[v] if cost[w] > s)
def greedy_views(lat: Lattice, k: int) -> Tuple[List[View], List[float]]:
"""Pick k views (besides the top view) by largest benefit.
Returns the views in the order of choice and the benefit of each choice.
Ties go to the view that comes first in the sorted order of views.
"""
stored = {lat.top} # @line L1
cost = lat.costs(stored)
picks: List[View] = []
gains: List[float] = []
for _ in range(k): # @line L2
best, best_b = None, -1.0
for v in lat.views:
if v in stored:
continue
b = _benefit(lat, cost, v) # @line L3
if b > best_b: # @line L4
best, best_b = v, b
if best is None:
break
stored.add(best) # @line L5
picks.append(best)
gains.append(best_b)
s = lat.size[best]
for w in lat.below[best]:
if cost[w] > s:
cost[w] = s
return picks, gains # @line L6
def greedy_per_space(lat: Lattice) -> List[Tuple[View, float, float]]:
"""Pick views by largest benefit per unit of space, while some benefit is positive.
Returns (view, space used so far, benefit so far) after each choice.
"""
stored = {lat.top}
cost = lat.costs(stored)
out = []
space = 0.0
total = 0.0
while True:
best, best_r = None, 0.0
for v in lat.views:
if v in stored:
continue
r = _benefit(lat, cost, v) / lat.size[v]
if r > best_r:
best, best_r = v, r
if best is None:
return out
b = _benefit(lat, cost, best)
stored.add(best)
space += lat.size[best]
total += b
out.append((best, space, total))
for w in lat.below[best]:
if cost[w] > lat.size[best]:
cost[w] = lat.size[best]
def best_k_views(lat: Lattice, k: int) -> Tuple[float, Tuple[View, ...]]:
"""The largest benefit of k views, by trying every set of k views."""
others = [v for v in lat.views if v != lat.top]
best = (-1.0, ())
for c in combinations(others, min(k, len(others))):
b = lat.benefit_of_set(c)
if b > best[0]:
best = (b, c)
return best
def best_within_space(lat: Lattice, space: float) -> float:
"""The largest benefit of a set of views of total size at most `space`, by brute force."""
others = [v for v in lat.views if v != lat.top]
best = 0.0
for m in range(1, len(others) + 1):
for c in combinations(others, m):
if sum(lat.size[v] for v in c) <= space:
best = max(best, lat.benefit_of_set(c))
return best
def greedy_bound(k: int) -> float:
"""1 - (1 - 1/k)^k, the guarantee of Theorem 4.1 of the paper."""
return 1 - (1 - 1 / k) ** k
def cube_lattice(dims: Sequence[str], size_of) -> Lattice:
"""The data cube lattice: one view per subset of the dimensions.
The view on a set A answers the view on every subset of A. `size_of`
maps a frozenset of dimensions to the size of that view.
"""
subsets = [frozenset(c) for m in range(len(dims) + 1) for c in combinations(dims, m)]
sizes = {s: size_of(s) for s in subsets}
edges = [(a, a - {x}) for a in subsets for x in a]
return Lattice(sizes, edges, frozenset(dims))
test_hru_greedy_view_selection.py 173 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hru-greedy-view-selection/. The authors are listed in prov/TY6PHM.jsonl.
import math
import unittest
from itertools import combinations
from random import Random
from hru_greedy_view_selection import (
Lattice,
best_k_views,
best_within_space,
cube_lattice,
greedy_bound,
greedy_per_space,
greedy_views,
)
def example_4_1():
"""The lattice of Example 4.1 (Fig. 7) of Harinarayan, Rajaraman and Ullman."""
sizes = {"a": 100, "b": 50, "c": 75, "d": 20, "e": 30, "f": 40, "g": 1, "h": 10}
edges = [("a", "b"), ("a", "c"), ("b", "d"), ("b", "e"), ("c", "e"), ("c", "f"),
("d", "g"), ("e", "g"), ("e", "h"), ("f", "h")]
return Lattice(sizes, edges, "a")
def example_4_2():
"""The lattice of Example 4.2 (Fig. 9): four chains of 20 views under b, c and d."""
sizes = {"a": 200, "b": 100, "c": 99, "d": 100}
edges = [("a", "b"), ("a", "c"), ("a", "d")]
heads = []
for chain in range(4):
prev = None
for i in range(20):
v = "x%d_%02d" % (chain, i)
sizes[v] = 100
if prev is not None:
edges.append((prev, v))
else:
heads.append(v)
prev = v
for parent, chain in [("b", 0), ("b", 1), ("c", 1), ("c", 2), ("d", 2), ("d", 3)]:
edges.append((parent, heads[chain]))
return Lattice(sizes, edges, "a")
def random_cube(rng, d):
dims = "pqrs"[:d]
dom = {x: rng.choice([2, 3, 5, 10, 20, 50]) for x in dims}
top = rng.randint(200, 3000)
def size_of(s):
return min(top, math.prod(dom[x] for x in s)) if s else 1
return cube_lattice(dims, size_of)
def random_dag(rng, n):
"""A random lattice-like order: view 0 on top, edges from lower to higher numbers."""
sizes = {0: 1000}
edges = []
for v in range(1, n):
parents = rng.sample(range(v), rng.randint(1, min(3, v)))
edges += [(p, v) for p in parents]
sizes[v] = rng.randint(1, min(sizes[p] for p in parents))
return Lattice(sizes, edges, 0)
class TestExamples(unittest.TestCase):
def test_example_4_1(self):
lat = example_4_1()
self.assertEqual(lat.total_cost([]), 800)
picks, gains = greedy_views(lat, 3)
self.assertEqual(picks, ["b", "f", "d"])
self.assertEqual(gains, [250, 70, 60])
self.assertEqual(lat.total_cost(picks), 420)
self.assertEqual(best_k_views(lat, 3)[0], 380)
def test_example_4_1_rounds(self):
lat = example_4_1()
from hru_greedy_view_selection import _benefit
cost = lat.costs([])
r1 = {v: _benefit(lat, cost, v) for v in "bcdefgh"}
self.assertEqual(r1, {"b": 250, "c": 125, "d": 160, "e": 210, "f": 120, "g": 99, "h": 90})
cost = lat.costs(["b"])
r2 = {v: _benefit(lat, cost, v) for v in "cdefgh"}
self.assertEqual(r2, {"c": 50, "d": 60, "e": 60, "f": 70, "g": 49, "h": 40})
cost = lat.costs(["b", "f"])
r3 = {v: _benefit(lat, cost, v) for v in "cdegh"}
self.assertEqual(r3, {"c": 25, "d": 60, "e": 50, "g": 49, "h": 30})
def test_example_4_2(self):
lat = example_4_2()
picks, gains = greedy_views(lat, 2)
self.assertEqual(picks[0], "c")
self.assertEqual(gains, [4141, 2100])
best, chosen = best_k_views(lat, 2)
self.assertEqual(best, 8200)
self.assertEqual(set(chosen), {"b", "d"})
self.assertGreaterEqual(sum(gains) / best, greedy_bound(2))
def test_bound_values(self):
self.assertEqual(greedy_bound(1), 1)
self.assertEqual(greedy_bound(2), 0.75)
self.assertGreater(greedy_bound(50), 1 - 1 / math.e)
class TestGuarantee(unittest.TestCase):
def check(self, lat, k):
picks, gains = greedy_views(lat, k)
self.assertAlmostEqual(sum(gains), lat.benefit_of_set(picks))
opt = best_k_views(lat, k)[0]
self.assertGreaterEqual(sum(gains) + 1e-9, greedy_bound(k) * opt)
self.assertLessEqual(sum(gains), opt + 1e-9)
return sum(gains), opt
def test_cubes(self):
rng = Random(2)
for _ in range(25):
lat = random_cube(rng, rng.choice([3, 4]))
for k in range(1, 4):
self.check(lat, k)
def test_random_orders(self):
rng = Random(9)
worse = 0
for _ in range(30):
lat = random_dag(rng, rng.randint(5, 11))
for k in range(1, 4):
g, opt = self.check(lat, k)
worse += g < opt - 1e-9
self.assertGreater(worse, 0)
def test_weights(self):
rng = Random(4)
for _ in range(20):
lat = random_cube(rng, 3)
lat.weight = {v: rng.randint(0, 5) for v in lat.views}
for k in range(1, 4):
self.check(lat, k)
def test_gains_do_not_grow(self):
rng = Random(6)
for _ in range(20):
lat = random_dag(rng, 12)
gains = greedy_views(lat, 6)[1]
for x, y in zip(gains, gains[1:]):
self.assertGreaterEqual(x, y)
class TestPerSpace(unittest.TestCase):
def test_space_bound(self):
rng = Random(8)
for trial in range(20):
lat = random_cube(rng, 3) if trial % 2 else random_dag(rng, 9)
others = [v for v in lat.views if v != lat.top]
table = []
for m in range(1, len(others) + 1):
for c in combinations(others, m):
table.append((sum(lat.size[v] for v in c), lat.benefit_of_set(c)))
for v, space, total in greedy_per_space(lat):
best = max([b for s, b in table if s <= space] + [0])
self.assertGreaterEqual(total + 1e-9, (1 - 1 / math.e) * best)
def test_brute_force_helper(self):
lat = example_4_1()
# d and e (space 20 + 30) save 160 + 140, more than b alone (250).
self.assertEqual(best_within_space(lat, 50), 300)
if __name__ == "__main__":
unittest.main()
History
Gray et al. proposed the data cube operator in 1996, and it raised the question of which parts of the cube to precompute. In the same year Venky Harinarayan, Anand Rajaraman and Jeffrey D. Ullman organized the views as a lattice, used the TPC-D benchmark as a running example, and gave the greedy algorithm with its bounds; the paper refers to a full version of 1995 for the proofs. Their analysis is a case of the bound of Nemhauser, Wolsey and Fisher (1978) for monotone submodular functions. Later work by Gupta and by Gupta, Harinarayan, Rajaraman and Ullman extended the method to indexes and to general view graphs.
References
- Venky Harinarayan, Anand Rajaraman and Jeffrey D. Ullman, Implementing data cubes efficiently, Proceedings of ACM SIGMOD 1996, 205 to 216, Section 3.2 (the linear cost model and the reduction from set cover), Section 4.1 and Fig. 6 (the benefit and the greedy algorithm), Examples 4.1 and 4.2 (Figs. 7 and 9), Section 4.3 (Theorem 4.1, the bound 1 - (1 - 1/k)^k, and Theorem 4.2 for benefit per unit space), Section 4.5 (query frequencies)
- An analysis of approximations for maximizing submodular set functions I, the greedy algorithm reaches 1 - (1 - 1/k)^k of the maximum of a monotone submodular function over sets of size k
- Selection of views to materialize in a data warehouse, the extension of the greedy method and its guarantee from the cube lattice to AND-OR view graphs
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 TY6PHM Edit this page History Report an error Markdown