Algorithmadvanced
AutoAdmin index selection
Also called Chaudhuri-Narasayya index tuning.
Pick indexes for a workload by finding the best ones for each query, then growing a configuration greedily with what-if costs.
- Time
- O((n^m + k n) q k) worst · averageO(n^m q) best
- Space
- O(q P) extra
- Where
- P = the number of admissible indexes; k = the largest number of indexes; m = the size of the exhaustive start; n = the number of candidate indexes; q = the number of statements in the workload
- Model
- Word RAM
- Properties
- deterministicnot exactnot externalnot in placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Surajit Chaudhuri, Vivek Narasayya, 1997
AutoAdmin index selection is the algorithm of the index tuning tool that Chaudhuri and Narasayya built for Microsoft SQL Server. Given a workload of queries and updates and a limit on the number of indexes, it returns a configuration of indexes with a low estimated cost. The index selection problem is NP-hard, so the tool is a heuristic made of three parts. Candidate selection treats each query alone as a workload and keeps the indexes of its best configuration. Configuration enumeration, Greedy, searches all configurations of candidates exhaustively and then adds one index at a time. Multi-column index generation builds wider indexes step by step from the narrower ones that were chosen. All costs come from the query optimizer by what-if calls, and atomic configurations let the tool derive most costs without a call.
In plain words
Suppose you can afford three indexes for a database, and you have a list of the queries that people run. Trying every set of three indexes would take far too many questions to the optimizer. So you first ask, for each query alone, "which indexes would help this query most?" Only those indexes stay in the game.
Then you build the set. You try all pairs of the remaining indexes and keep the best pair. You then add the single index that helps the most, as long as it helps at all and the set is not full. Wide indexes on two columns are tried only if their first column was a good index on its own. Each "how much would this cost?" goes to the optimizer as if the indexes existed, and answers that can be worked out from earlier answers are not asked again.
The problem
The input is a workload of weighted statements, a limit on the number of indexes, and an optimizer that, for a statement and a configuration of hypothetical indexes, returns the estimated cost . The goal is a configuration with and a small total cost . Updates are in the workload, so an index can raise the total cost.
Each optimizer call is expensive, so the tool must make few of them. The problem itself, with its NP-hardness and its known bounds, is on the page on index selection. This page is about the AutoAdmin algorithm.
The algorithm
TUNE(W, k, m, width)- 1
chosen ← ∅; pool ← ∅ - 2
for j ← 1 to width do - 3
pool ← pool ∪ the admissible indexes of width j ▷ width 1: the indexable columns; width j > 1: MC-LEAD - 4
candidates ← chosen; for each statement Q in W do - 5
candidates ← candidates ∪ ENUMERATE({Q}, the indexes of pool that Q can use, k, m) - 6
chosen ← ENUMERATE(W, candidates ∪ chosen, k, m)
ENUMERATE(W, S, k, m) ▷ Greedy(m, k)- 1
C ← the configuration of at most m indexes of S with the least Cost(W, C), by exhaustive search - 2
while |C| < k do - 3
i ← the index of S \ C with the least Cost(W, C ∪ {i}) - 4
if Cost(W, C ∪ {i}) ≥ Cost(W, C) then stop - 5
C ← C ∪ {i} - 6
return C
- 1
opt(Q, C) ← the least opt(Q, A) over the atomic configurations A ⊆ C, each a cached what-if call
- Admissible indexes. In the first iteration they are the single-column indexes on the indexable columns, those that appear in the predicates of the workload. In iteration , the MC-LEAD rule of the paper forms an index of width from a chosen index of width by adding one more column of the workload. So is considered only if was chosen.
- Candidate selection. A query alone is a workload of one, and the tool runs its own enumeration on it. The indexes of the best configuration for that query become candidates. This prunes the search to indexes that are best for at least one query.
- Greedy. With it is plain greedy, and with it is exhaustive search over the candidates. The paper reports: "We found that m=2 produced very good solutions" (a measurement on its workloads).
- Atomic configurations. An atomic configuration of a query is a set of indexes that one plan of the query can use together. The paper derives the cost of a query in a large configuration as the least cost over its atomic subsets, and limits these subsets (for example, by the number of indexes per table that they may hold) so that few what-if calls are needed. In the optimizer model on this page, a plan uses one index, so the atomic configurations are the single indexes, and the cost of an update is the sum of the maintenance costs of the indexes it changes.
Example
A table has 100,000 rows and the columns , , and with 1,000, 100, 10 and 50,000 distinct values. A full scan costs 5,000. The workload has three queries and one update, and , , width 2:
| statement | weight | the best single index for it | cost |
|---|---|---|---|
| : , reads | 50 | , covering | 8 |
| : and | 30 | , covering | 3.05 |
| : in a range of 0.1%, reads | 20 | , covering | 8 |
| : update of | 10 | none; 4 more per index that holds | 1 |
With no index, the total is .
- Width 1. The admissible indexes are , and . Alone, and choose (cost 103 each, since about 100 rows match), and chooses (cost 103). The candidates are , and the enumeration chooses both, with a total of .
- Width 2. MC-LEAD extends to , and , and to , and . Alone, chooses , chooses , and chooses . With the earlier choice, the candidates are , , , and .
- Enumeration. With , L7 tries every pair. The best is , with . The pair serves almost for free but costs for and 5 for each update, a total of 5,451.5.
An exhaustive search over every configuration of at most two indexes of width at most 2 also gives 3,660, so here the tool finds the optimum. It made 21 what-if calls. The search costed 84 distinct pairs of a statement and a configuration, so without atomic configurations it would have needed 84 calls.
Measurement. On 200 random instances with two tables and 3 to 7 statements (seeds 0 to 199, , , width 2), the tool found the optimum of the exhaustive search on 94 instances. The median ratio of its cost to the optimum was 1.008, and the worst was 16.6. On average it made 25.6 what-if calls against 168.3 distinct statement and configuration pairs. With it found the optimum on 93 instances and with on 95.
Correctness
The proofs are in proofs/correctness.md. The main points:
- Exact costs (theorem). In a model where a plan uses the indexes of one atomic configuration, the cost of a query in any configuration is the least cost over its atomic subsets. So the derived costs equal the optimizer's costs, and the cache changes no value.
- Bounded calls (theorem). With single-index atomic configurations, the tool makes at most what-if calls.
- Greedy (theorem). The result has at most indexes, is at least as good as every configuration of at most candidates, and, if it has fewer than indexes, no single candidate lowers its cost. With it is the optimum over the candidates.
- No optimality (heuristic). The tool can miss the optimum. An index that is second best for two queries but serves both is never a candidate, and MC-LEAD never forms if was not chosen. Both cases occur in the measurement above: the worst instance needed for two queries whose best single indexes were and .
Proof: The AutoAdmin tool computes exact what-if costs from atomic configurations and returns a valid configuration that Greedy(m, k) cannot improve by one indexfull
We use the notation of the page and the code. A workload is a list of weighted statements , each a select or an update on one table. A configuration is a set of indexes. is the cost that the optimizer model (WhatIf.optimize) gives to when exactly the indexes of exist, and . The tool is asked for a configuration of at most indexes with a small cost. Finding the minimum is NP-hard (Piatetsky-Shapiro, 1983, and Comer, 1978), so the tool is a heuristic, and what we prove is that its costs are exact and its output is valid and locally best.
Lemma 1 (atomic configurations). For every statement and configuration , query_cost(Q, C) equals .
Proof. For a select, the model costs a full scan and, for each index of on the table of that it can use, one plan with that index, and returns the minimum. A plan uses one index, so its cost depends only on that index: is the minimum of the scan and the plan with . Hence , which is what L13 computes; an index that cannot use gives the scan, so skipping it changes nothing. For an update, the model charges plus a fixed amount for each index on the table that holds a changed column, so , which is the sum the code takes. The cache returns the value of an earlier call with the same key, and the model has no state, so the cache does not change any value.
So the atomic configurations of a select in this model are and the single indexes, and of an update the single indexes. Lemma 1 is the property that the paper requires of atomic configurations: the cost in any configuration follows from the costs in its atomic subsets without a new optimizer call.
Lemma 2 (number of what-if calls). If is the set of all indexes that the tool considers (the final pool), the tool makes at most what-if calls.
Proof. Every call has a key with or , , and each key is computed once.
Without atomic configurations, each pair of a statement and a configuration that the search costs needs its own call. The tests check that this number (len(tool.pairs)) is more than three times the number of calls.
Lemma 3 (Greedy(m, k)). Let be a set of candidates and the result of enumerate(W, S, k). Then:
- and .
- for every with , and in particular for .
- If , no single index of lowers the cost: for all .
- If , has the least cost among all subsets of with at most indexes.
Proof. L7 tries every subset of of size at most and keeps one of least cost, starting from ; this gives (2) for the start. Each step of L8 to L11 adds one index of and is taken only if it lowers the cost strictly, so the cost never rises, which keeps (2), and the size grows by one up to , which gives (1). The loop ends at size , or when L10 finds no index that lowers the cost, which is (3). If , L7 is already the exhaustive search over all subsets of size at most , and the loop cannot improve it without exceeding , which is (4). The loop runs at most times, so the procedure ends.
Theorem 1 (the tool). run ends and returns a configuration of at most indexes, each in the pool of admissible indexes, whose cost is at most the cost with no index, and to which no single candidate can be added with a lower cost if it has fewer than indexes. Each candidate is an index of the best configuration that Greedy(m, k) finds for some single statement, or an index chosen in an earlier iteration.
Proof. There are width iterations. In each, the per-statement calls at L5 and the workload call at L6 are calls of enumerate, which end by Lemma 3. The candidates are the union of their results and of the earlier choice, so they lie in the pool. The final configuration is the result of L6 in the last iteration, so Lemma 3, parts (1) to (3), gives the claims, and Lemma 1 shows that the costs it compares are the optimizer's costs.
What the tool does not guarantee. The output need not be optimal, even among the indexes of the pool. Two ways it can miss are shown by the tests' search over random instances:
- Candidate selection. An index that is second best for each of two statements, but serves both, is not the best for either alone, so L5 does not make it a candidate.
- Multi-column indexes. MC-LEAD forms an index of width only from a chosen index of width . If no index on the leading column was chosen, no wider index with that leading column is formed.
The tests compare the tool with an exhaustive search over all configurations of at most indexes from all admissible indexes, and check that the tool is never better than the optimum (a check of the search and the costs), never worse than no index, and finds the optimum on at least 15 of 40 random instances. They also check Lemma 1 against the optimizer model on random configurations, part (4) of Lemma 3, and that more steps of the greedy loop never raise the cost.
Complexity
- Enumeration. L7 costs configurations, and the loop at most more. Each configuration is costed over statements, with up to cached look-ups each.
- Candidate selection runs the enumeration once per statement, on the few indexes that the statement can use.
- What-if calls are the real cost, since each is an optimizer call. They are at most with single-index atomic configurations, and the paper's limits on atomic configurations keep them small in general.
- Space. The cache of what-if costs, entries.
Properties
- Deterministic. Ties are broken by a fixed order of the indexes.
- Not exact. It is a heuristic for an NP-hard problem; its results are at least as good as no index and locally best for one added index.
- Optimizer-driven. It uses the optimizer's own cost estimates, so it chooses indexes that the optimizer will in fact use. Errors in the estimates become errors in the choice.
- Offline. It needs the workload in advance, as a trace or a sample.
Variants and improvements
- Database Engine Tuning Advisor. The successor tool in later versions of SQL Server also chooses materialized views and partitionings, with the same candidate selection and enumeration ideas (view selection).
- Space limit. A limit on storage instead of on the number of indexes; the greedy step then compares benefit per unit of space, as on the index selection page.
- Workload compression. Large traces are reduced to a sample of representative statements before tuning.
- Integer programming. Later tools solve the enumeration exactly over the candidates, with the same what-if costs.
When to use it
Use this approach to recommend indexes for a known workload, when the optimizer can cost hypothetical indexes and when the number of indexable columns is too large for exhaustive search. It is the pattern of most commercial and open-source index advisors. If the workload is not known in advance, adaptive methods such as database cracking build indexes as queries arrive. If the workload is small, an exhaustive search or an integer program over the candidates is affordable and exact.
Pitfalls
- Pruned candidates. Candidate selection keeps only the best indexes of each query. A shared index that is second best for many queries is lost. Widening the per-query search to the best few configurations reduces this.
- The leading column. MC-LEAD builds wide indexes only on chosen narrow ones. If the useful leading column was not chosen at width 1, the wide index is never tried.
- Bad estimates. The tool trusts the optimizer's cardinality estimates. If they are wrong, it can choose indexes that are useless at run time. Check a recommendation on real runs.
- Updates. A workload without its updates makes every index look free. Include the inserts, updates and deletes, with their real weights.
- Many what-if calls. Without atomic configurations and a cache, the number of optimizer calls grows with the number of configurations, not with the number of indexes, and the tool becomes too slow.
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/autoadmin-index-selection/. The authors are listed in prov/Q7Z4FQ.jsonl.
"""The index selection tool of Chaudhuri and Narasayya (VLDB 1997).
The tool has three parts:
1. Candidate selection: each query alone is a workload of one, and the
indexes of its best configuration become candidates.
2. Configuration enumeration, Greedy(m, k): the best configuration of m
indexes by exhaustive search, then one index at a time while the cost
falls, up to k indexes.
3. Multi-column indexes, built up by width: the indexes of width j are the
chosen indexes of width j - 1 with one more column (the MC-LEAD rule).
Costs come from a what-if function, which stands in for the query optimizer
with hypothetical indexes. The optimizer model on this page uses at most one
index per query, so the atomic configurations of a query are the single
indexes, and the cost of a query in any configuration is the minimum over
them. Each distinct (query, atomic configuration) pair costs one what-if call.
"""
from dataclasses import dataclass, field
from itertools import combinations
from typing import Dict, FrozenSet, Iterable, List, Optional, Sequence, Set, Tuple
ROWS_PER_PAGE = 20
Index = Tuple[str, Tuple[str, ...]] # (table, columns in key order)
@dataclass(frozen=True)
class Table:
name: str
rows: int
distinct: Tuple[Tuple[str, int], ...] # (column, number of distinct values)
def ndv(self, col: str) -> int:
return dict(self.distinct)[col]
@dataclass(frozen=True)
class Select:
weight: float
table: str
eq: Tuple[str, ...] = () # columns with an equality predicate
rng: Optional[str] = None # column with a range predicate
rng_sel: float = 1.0
out: Tuple[str, ...] = () # other columns the query reads
def indexable(self) -> Set[str]:
return set(self.eq) | ({self.rng} if self.rng else set())
def needed(self) -> Set[str]:
return self.indexable() | set(self.out)
@dataclass(frozen=True)
class Update:
weight: float
table: str
cols: Tuple[str, ...] # the columns it changes
class WhatIf:
"""A toy optimizer that costs a query under hypothetical indexes."""
def __init__(self, tables: Iterable[Table], maint: float = 4.0):
self.tables: Dict[str, Table] = {t.name: t for t in tables}
self.maint = maint
self.calls = 0
self.cache: Dict[Tuple[object, FrozenSet[Index]], float] = {}
def index_cost(self, q: Select, ix: Index) -> Optional[float]:
"""The cost of the plan for q that uses ix, or None if ix is of no use."""
t = self.tables[q.table]
table, cols = ix
if table != q.table:
return None
sel, used, pos = 1.0, 0, 0
while pos < len(cols) and cols[pos] in q.eq:
sel /= t.ndv(cols[pos])
used, pos = used + 1, pos + 1
if pos < len(cols) and cols[pos] == q.rng:
sel *= q.rng_sel
used += 1
if used == 0:
return None
rows = sel * t.rows
covering = q.needed() <= set(cols)
return 3.0 + rows * (1.0 / ROWS_PER_PAGE if covering else 1.0)
def optimize(self, q, config: FrozenSet[Index]) -> float:
"""The optimizer's cost for q with exactly the indexes in config."""
t = self.tables[q.table]
if isinstance(q, Update):
touched = [ix for ix in config if ix[0] == q.table and set(ix[1]) & set(q.cols)]
return 1.0 + self.maint * len(touched)
best = t.rows / ROWS_PER_PAGE # a full scan
for ix in config:
c = self.index_cost(q, ix)
if c is not None and c < best:
best = c
return best
def call(self, q, config: FrozenSet[Index]) -> float:
"""A what-if call, with a cache, as the tool makes it."""
key = (q, config)
if key not in self.cache:
self.calls += 1
self.cache[key] = self.optimize(q, config)
return self.cache[key]
class Tool:
def __init__(self, whatif: WhatIf, workload: Sequence, k: int, m: int = 2, width: int = 2):
self.w = whatif
self.workload = list(workload)
self.k, self.m, self.width = k, m, width
self.pairs: Set[Tuple[object, FrozenSet[Index]]] = set() # (query, configuration) pairs costed
# ----- costs from atomic configurations -----
def query_cost(self, q, config: FrozenSet[Index]) -> float:
if isinstance(q, Update): # maintenance adds up per index
return 1.0 + sum(self.w.call(q, frozenset([ix])) - 1.0 for ix in config
if ix[0] == q.table)
best = self.w.call(q, frozenset()) # @line L13
for ix in config:
if ix[0] == q.table and self.w.index_cost(q, ix) is not None:
best = min(best, self.w.call(q, frozenset([ix]))) # @line L13
return best
def cost(self, workload: Sequence, config: Iterable[Index]) -> float:
c = frozenset(config)
self.pairs.update((q, c) for q in workload)
return sum(q.weight * self.query_cost(q, c) for q in workload)
# ----- Greedy(m, k) -----
def enumerate(self, workload: Sequence, cands: Iterable[Index], k: int) -> FrozenSet[Index]:
cands = sorted(set(cands))
best, best_cost = frozenset(), self.cost(workload, ())
for r in range(1, min(self.m, k) + 1): # @line L7
for s in combinations(cands, r):
c = self.cost(workload, s)
if c < best_cost:
best, best_cost = frozenset(s), c
while len(best) < k: # @line L8
step, step_cost = None, best_cost
for ix in cands: # @line L9
if ix not in best:
c = self.cost(workload, best | {ix})
if c < step_cost:
step, step_cost = ix, c
if step is None: # @line L10
break
best, best_cost = best | {step}, step_cost # @line L11
return best # @line L12
# ----- candidate selection and multi-column indexes -----
def indexable_columns(self, table: str, lead: bool) -> Set[str]:
out: Set[str] = set()
for q in self.workload:
if isinstance(q, Select) and q.table == table:
out |= q.indexable() if lead else q.needed()
return out
def admissible(self, j: int, chosen: Iterable[Index]) -> Set[Index]:
if j == 1:
return {(t, (c,)) for t in self.w.tables for c in self.indexable_columns(t, True)}
out = set()
for t, cols in chosen: # MC-LEAD
if len(cols) == j - 1:
for c in self.indexable_columns(t, False):
if c not in cols:
out.add((t, cols + (c,)))
return out
def relevant(self, q, indexes: Iterable[Index]) -> List[Index]:
if not isinstance(q, Select):
return []
return [ix for ix in indexes if self.w.index_cost(q, ix) is not None]
def run(self) -> FrozenSet[Index]:
chosen: FrozenSet[Index] = frozenset() # @line L1
pool: Set[Index] = set()
self.trace = []
for j in range(1, self.width + 1): # @line L2
pool |= self.admissible(j, chosen) # @line L3
cands: Set[Index] = set(chosen)
for q in self.workload: # @line L4
cands |= self.enumerate([q], self.relevant(q, pool), self.k) # @line L5
chosen = self.enumerate(self.workload, cands, self.k) # @line L6
self.trace.append((j, sorted(cands), sorted(chosen)))
return chosen
def all_indexes(tool: Tool) -> List[Index]:
"""Every index of width at most tool.width that some select query can use."""
out = set()
for t in tool.w.tables:
lead = tool.indexable_columns(t, True)
cols = sorted(tool.indexable_columns(t, False))
for c in lead:
out.add((t, (c,)))
for wdt in range(2, tool.width + 1):
for ix in list(out):
if ix[0] == t and len(ix[1]) == wdt - 1:
for c in cols:
if c not in ix[1]:
out.add((t, ix[1] + (c,)))
return sorted(out)
def brute_force(tool: Tool) -> Tuple[float, FrozenSet[Index]]:
"""The optimum over all configurations of at most k indexes."""
idx = all_indexes(tool)
best, best_cost = frozenset(), tool.cost(tool.workload, ())
for r in range(1, tool.k + 1):
for s in combinations(idx, r):
c = tool.cost(tool.workload, s)
if c < best_cost - 1e-9:
best, best_cost = frozenset(s), c
return best_cost, best
test_autoadmin_index_selection.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/autoadmin-index-selection/. The authors are listed in prov/Q7Z4FQ.jsonl.
import random
import unittest
from itertools import combinations
from autoadmin_index_selection import (Select, Table, Tool, Update, WhatIf,
all_indexes, brute_force)
def page_example():
t = Table("T", 100000, (("a", 1000), ("b", 100), ("c", 10), ("d", 50000)))
w = [Select(50, "T", eq=("a",), out=("d",)),
Select(30, "T", eq=("a", "b")),
Select(20, "T", rng="d", rng_sel=0.001, out=("c",)),
Update(10, "T", ("b",))]
return [t], w
def random_instance(rng):
cols = ["a", "b", "c", "d", "e"]
t = Table("T", 100000, tuple((c, rng.choice([2, 10, 100, 1000, 50000])) for c in cols))
s = Table("S", 20000, tuple((c, rng.choice([2, 10, 100, 1000])) for c in ["x", "y", "z"]))
w = []
for _ in range(rng.randrange(3, 7)):
tab, cs = (t, cols) if rng.random() < 0.7 else (s, ["x", "y", "z"])
eq = tuple(rng.sample(cs, rng.randrange(0, 3)))
rest = [c for c in cs if c not in eq]
rc = rng.choice(rest) if (rng.random() < 0.5 or not eq) else None
pool = [c for c in rest if c != rc]
out = tuple(rng.sample(pool, min(len(pool), rng.randrange(0, 2))))
w.append(Select(rng.randrange(1, 50), tab.name, eq, rc, rng.choice([0.001, 0.01, 0.1]), out))
for _ in range(rng.randrange(0, 2)):
w.append(Update(rng.randrange(1, 200), "T", tuple(rng.sample(cols, 1))))
return [t, s], w
class TestExample(unittest.TestCase):
def test_page_example(self):
tabs, w = page_example()
wi = WhatIf(tabs)
tool = Tool(wi, w, k=2, m=2, width=2)
chosen = tool.run()
self.assertEqual(tool.trace[0][2], [("T", ("a",)), ("T", ("d",))])
self.assertEqual(tool.trace[1][1], [("T", ("a",)), ("T", ("a", "b")), ("T", ("a", "d")),
("T", ("d",)), ("T", ("d", "c"))])
self.assertEqual(sorted(chosen), [("T", ("a", "d")), ("T", ("d", "c"))])
self.assertEqual(tool.cost(w, ()), 50 * 5000 + 30 * 5000 + 20 * 5000 + 10)
self.assertEqual(tool.cost(w, [("T", ("a",)), ("T", ("d",))]), 10310)
self.assertEqual(tool.cost(w, chosen), 3660)
self.assertEqual(tool.cost(w, [("T", ("a", "b")), ("T", ("d", "c"))]), 5451.5)
self.assertEqual(wi.calls, 21)
self.assertEqual(len(tool.pairs), 84)
self.assertEqual(brute_force(Tool(WhatIf(tabs), w, k=2))[0], 3660)
class TestParts(unittest.TestCase):
def test_atomic_configurations_give_the_optimizer_cost(self):
"""cost(Q, C) from single-index what-if calls equals the optimizer on all of C."""
rng = random.Random(1)
for seed in range(40):
tabs, w = random_instance(random.Random(seed))
wi = WhatIf(tabs)
tool = Tool(wi, w, k=3)
idx = all_indexes(tool)
for _ in range(20):
c = frozenset(rng.sample(idx, min(len(idx), rng.randrange(0, 5))))
for q in w:
self.assertAlmostEqual(tool.query_cost(q, c), wi.optimize(q, c))
def test_greedy_with_m_at_least_k_is_exhaustive(self):
for seed in range(25):
tabs, w = random_instance(random.Random(seed))
tool = Tool(WhatIf(tabs), w, k=2, m=2)
cands = all_indexes(tool)
got = tool.cost(w, tool.enumerate(w, cands, 2))
best = min(tool.cost(w, s) for r in range(3) for s in combinations(cands, r))
self.assertAlmostEqual(got, best)
def test_greedy_steps_only_lower_the_cost(self):
for seed in range(25):
tabs, w = random_instance(random.Random(seed))
tool = Tool(WhatIf(tabs), w, k=4, m=1)
cands = all_indexes(tool)
prev = tool.cost(w, ())
for k in range(1, 5):
c = tool.cost(w, tool.enumerate(w, cands, k))
self.assertLessEqual(c, prev + 1e-9)
prev = c
self.assertLessEqual(len(tool.enumerate(w, cands, 4)), 4)
def test_mc_lead_extends_chosen_indexes(self):
tabs, w = page_example()
tool = Tool(WhatIf(tabs), w, k=2)
ext = tool.admissible(2, [("T", ("a",))])
self.assertEqual(sorted(ext), [("T", ("a", "b")), ("T", ("a", "c")), ("T", ("a", "d"))])
class TestAgainstBruteForce(unittest.TestCase):
def test_tool_against_the_optimum(self):
found, ratios = 0, []
calls = pairs = 0
for seed in range(40):
tabs, w = random_instance(random.Random(seed))
wi = WhatIf(tabs)
tool = Tool(wi, w, k=3, m=2, width=2)
chosen = tool.run()
self.assertLessEqual(len(chosen), 3)
got = tool.cost(w, chosen)
best, _ = brute_force(Tool(WhatIf(tabs), w, k=3, width=2))
self.assertGreaterEqual(got, best - 1e-6) # never better than the optimum
self.assertLessEqual(got, tool.cost(w, ()) + 1e-9) # never worse than no index
found += abs(got - best) < 1e-6
ratios.append(got / best)
calls += wi.calls
pairs += len(tool.pairs)
self.assertGreaterEqual(found, 15) # a heuristic: it often, not always, finds the optimum
self.assertLess(calls * 3, pairs) # atomic configurations save what-if calls
if __name__ == "__main__":
unittest.main()
History
Surajit Chaudhuri and Vivek Narasayya of the AutoAdmin project at Microsoft Research presented the tool at VLDB 1997, and it shipped as the Index Tuning Wizard of SQL Server 7.0. Their SIGMOD 1998 paper described the what-if interface that lets the optimizer cost indexes that do not exist. Earlier work had shown that optimal index selection is NP-complete (Comer, 1978; Piatetsky-Shapiro, 1983), and had often used cost models apart from the optimizer. The AutoAdmin tool made the optimizer itself the cost model, which most later index advisors do too.
References
- Surajit Chaudhuri and Vivek Narasayya, An efficient, cost-driven index selection tool for Microsoft SQL Server, Proceedings of the 23rd International Conference on Very Large Data Bases (VLDB 1997), pp. 146 to 155: Section 3 (atomic configurations and the reduction of optimizer calls), Section 4 (candidate index selection per query), Section 5 (the Greedy(m, k) enumeration), Section 6 (multi-column indexes and MC-LEAD), Section 7 (experiments with SQL Server 7.0)
- Surajit Chaudhuri and Vivek Narasayya, AutoAdmin what-if index analysis utility, Proceedings of ACM SIGMOD 1998, pp. 367 to 378, the hypothetical indexes and the optimizer interface that the tool uses for its costs
- Gregory Piatetsky-Shapiro, The optimal selection of secondary indices is NP-complete, ACM SIGMOD Record 13(2) (1983), pp. 72 to 75, the NP-completeness of optimal index selection
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 Q7Z4FQ Edit this page History Report an error Markdown