ltranslate the query into its internal form. This is then translated into relational algebra.
lParser checks syntax, verifies relations
nEvaluation
lThe query-execution engine takes a query-evaluation plan, executes that plan, and returns the answers to the query.
Basic Steps in Query Processing : Optimization
nA relational algebra expression may have many equivalent expressions
lE.g., sbalance<2500(Õbalance(account)) is equivalent to Õbalance(sbalance<2500(account))
nEach relational algebra operation can be evaluated using one of several different algorithms
lCorrespondingly, a relational-algebra expression can be evaluated in many ways.
nAnnotated expression specifying detailed evaluation strategy is called an evaluation-plan.
lE.g., can use an index on balance to find accounts with balance < 2500,
lor can perform complete relation scan and discard accounts with balance ³ 2500
nQuery Optimization: Amongst all equivalent evaluation plans choose the one with lowest cost.
l Cost is estimated using statistical information from the database catalog
4e.g. number of tuples in each relation, size of tuples, etc.
nIn this chapter we study
lHow to measure query costs
lAlgorithms for evaluating relational algebra operations
lHow to combine algorithms for individual operations in order to evaluate a complete expression
nIn Chapter 14
lWe study how to optimize queries, that is, how to find an evaluation plan with lowest estimated cost
Measures of Query Cost
nCost is generally measured as total elapsed time for answering query
lMany factors contribute to time cost
4disk accesses, CPU, or even network communication
nTypically disk access is the predominant cost, and is also relatively easy to estimate. Measured by taking into account
lNumber of seeks * average-seek-cost
lNumber of blocks read * average-block-read-cost
lNumber of blocks written * average-block-write-cost
4Cost to write a block is greater than cost to read a block
–data is read back after being written to ensure that the write was successful
nFor simplicity we just use the number of block transfers from disk and the number of seeks as the cost measures
ltT – time to transfer one block
ltS – time for one seek
lCost for b block transfers plus S seeks b * tT + S * tS
nWe ignore CPU costs for simplicity
lReal systems do take CPU cost into account
nWe do not include cost to writing output to disk in our cost formulae
nSeveral algorithms can reduce disk IO by using extra buffer space
lAmount of real memory available to buffer depends on other concurrent queries and OS processes, known only during execution
4We often use worst case estimates, assuming only the minimum amount of memory needed for the operation is available
nRequired data may be buffer resident already, avoiding disk I/O
lBut hard to take into account for cost estimation
Selection Operation
nFile scan – search algorithms that locate and retrieve records that fulfill a selection condition.
nAlgorithm A1 (linear search). Scan each file block and test all records to see whether they satisfy the selection condition.
lCost estimate = br block transfers + 1 seek
4br denotes number of blocks containing records from relation r
lIf selection is on a key attribute, can stop on finding record
4cost = (br /2) block transfers + 1 seek
lLinear search can be applied regardless of
4selection condition or
4ordering of records in the file, or
4availability of indices
nA2 (binary search). Applicable if selection is an equality comparison on the attribute on which file is ordered.
lAssume that the blocks of a relation are stored contiguously
lCost estimate (number of disk blocks to be scanned):
4cost of locating the first tuple by a binary search on the blocks
–élog2(br)ù * (tT + tS)
4If there are multiple records satisfying selection
–Add transfer cost of the number of blocks containing records that satisfy selection condition
–Will see how to estimate this cost in Chapter 14
Selections Using Indices
nIndex scan – search algorithms that use an index
lselection condition must be on search-key of index.
nA3 (primary index on candidate key, equality). Retrieve a single record that satisfies the corresponding equality condition
lCost = (hi+ 1) * (tT + tS)
nA4 (primary index on nonkey, equality) Retrieve multiple records.
lRecords will be on consecutive blocks
4Let b = number of blocks containing matching records
lCost = hi * (tT + tS)+ tS + tT * b
nA5 (equality on search-key of secondary index).
lRetrieve a single record if the search-key is a candidate key
4Cost = (hi+ 1) * (tT + tS)
lRetrieve multiple records if search-key is not a candidate key
4each of n matching records may be on a different block
4Cost = (hi+ n) * (tT + tS)
–Can be very expensive!
Selections Involving Comparisons
nCan implement selections of the form sA£V (r) or sA ³V(r) by using
l a linear file scan or binary search,
l or by using indices in the following ways:
nA6 (primary index, comparison). (Relation is sorted on A)
4For sA ³ V(r) use index to find first tuple ³ v and scan relation sequentially from there
4For sA£V (r) just scan relation sequentially till first tuple > v; do not use index
nA7 (secondary index, comparison).
4For sA ³ V(r) use index to find first index entry ³ v and scan index sequentially from there, to find pointers to records.
4For sA£V (r) just scan leaf pages of index finding pointers to records, till first entry > v
4In either case, retrieve records that are pointed to
–requires an I/O for each record
– Linear file scan may be cheaper
Implementation of Complex Selections
nConjunction: sq1Ùq2Ù. . . qn(r)
nA8 (conjunctive selection using one index).
lSelect a combination of qi and algorithms A1 through A7 that results in the least cost for sqi (r).
lTest other conditions on tuple after fetching it into memory buffer.
nA9 (conjunctive selection using multiple-key index).
lUse appropriate composite (multiple-key) index if available.
nA10 (conjunctive selection by intersection of identifiers).
lRequires indices with record pointers.
lUse corresponding index for each condition, and take intersection of all the obtained sets of record pointers.
lThen fetch records from file
lIf some conditions do not have appropriate indices, apply test in memory.
Algorithms for Complex Selections
nDisjunction:sq1Úq2 Ú. . . qn (r).
nA11 (disjunctive selection by union of identifiers).
lApplicable if all conditions have available indices.
4Otherwise use linear scan.
lUse corresponding index for each condition, and take union of all the obtained sets of record pointers.
lThen fetch records from file
nNegation: sØq(r)
lUse linear scan on file
lIf very few records satisfy Øq, and an index is applicable to q
4 Find satisfying records using index and fetch from file
Sorting
nWe may build an index on the relation, and then use the index to read the relation in sorted order. May lead to one disk block access for each tuple.
nFor relations that fit in memory, techniques like quicksort can be used. For relations that don’t fit in memory, external sort-merge is a good choice.
External Sort-Merge
nCreate sortedruns. Let i be 0 initially. Repeatedly do the following till the end of the relation: (a) Read M blocks of relation into memory (b) Sort the in-memory blocks (c) Write sorted data to run Ri; increment i. Let the final value of i be N
nMerge the runs (next slide)…..
nMerge the runs (N-way merge). We assume (for now) that N < M.
nUse N blocks of memory to buffer input runs, and 1 block to buffer output. Read the first block of each run into its buffer page
nrepeat
nSelect the first record (in sort order) among all buffer pages
nWrite the record to the output buffer. If the output buffer is full write it to disk.
nDelete the record from its input buffer page. If the buffer page becomes empty then read the next block (if any) of the run into the buffer.
nuntil all input buffer pages are empty:
nIf N³M, several merge passes are required.
lIn each pass, contiguous groups of M - 1 runs are merged.
lA pass reduces the number of runs by a factor of M -1, and creates runs longer by the same factor.
4E.g. If M=11, and there are 90 runs, one pass reduces the number of runs to 9, each 10 times the size of the initial runs
lRepeated passes are performed till all runs have been merged into one.
Example: External Sorting Using Sort-Merge
nCost analysis:
lTotal number of merge passes required: élogM–1(br/M)ù.
lBlock transfers for initial run creation as well as in each pass is 2br
4for final pass, we don’t count write cost
–we ignore final write cost for all operations since the output of an operation may be sent to the parent operation without being written to disk
4Thus total number of block transfers for external sorting: br ( 2 élogM–1(br / M)ù + 1)
lSeeks: next slide
nCost of seeks
lDuring run generation: one seek to read each run and one seek to write each run
4 2 ébr / Mù
lDuring the merge phase
4Buffer size: bb (read/write bb blocks at a time)
4Need 2 ébr / bbù seeks for each merge pass
–except the final one which does not require a write
4Total number of seeks: 2 ébr / Mù + ébr / bbù (2 élogM–1(br / M)ù -1)
Join Operation
nSeveral different algorithms to implement joins
lNested-loop join
lBlock nested-loop join
lIndexed nested-loop join
lMerge-join
lHash-join
nChoice based on cost estimate
nExamples use the following information
lNumber of records of customer: 10,000 depositor: 5000
lNumber of blocks of customer: 400 depositor: 100
Nested-Loop Join
nTo compute the theta join rqs for each tuple tr in r do begin for each tuple tsin s do begin test pair (tr,ts) tosee if they satisfy the join condition q if they do, add tr• tsto the result. end end
nr is called the outerrelation and s the inner relation of the join.
nRequires no indices and can be used with any kind of join condition.
nExpensive since it examines every pair of tuples in the two relations.
nIn the worst case, if there is enough memory only to hold one block of each relation, the estimated cost is nr*bs + br block transfers, plus nr+ br seeks
nIf the smaller relation fits entirely in memory, use that as the inner relation.
l Reduces cost to br + bsblock transfers and 2 seeks
nAssuming worst case memory availability cost estimate is
nIf smaller relation (depositor) fits entirely in memory, the cost estimate will be 500 block transfers.
nBlock nested-loops algorithm (next slide) is preferable.
Block Nested-Loop Join
nVariant of nested-loop join in which every block of inner relation is paired with every block of outer relation.
for each block Brofr do begin for each block Bsof s do begin for each tuple trin Br do begin for each tuple tsin Bsdo begin Check if (tr,ts) satisfy the join condition if they do, add tr• tsto the result. end end end end
lEach block in the inner relation s is read once for each block in the outer relation (instead of once for each tuple in the outer relation
nBest case: br+ bsblock transfers + 2 seeks.
nImprovements to nested loop and block nested loop algorithms:
lIn block nested-loop, use M — 2 disk blocks as blocking unit for outer relations, where M = memory size in blocks; use remaining two blocks to buffer inner relation and output
lCPU cost likely to be less than that for block nested loops join
Merge-Join
nSort both relations on their join attribute (if not already sorted on the join attributes).
nMerge the sorted relations to join them
nJoin step is similar to the merge stage of the sort-merge algorithm.
nMain difference is handling of duplicate values in join attribute — every pair with same value on join attribute must be matched
nDetailed algorithm in book
nCan be used only for equi-joins and natural joins
nEach block needs to be read only once (assuming all tuples for any given value of the join attributes fit in memory
nThus the cost of merge join is: br + bs block transfers + ébr / bbù + ébs / bbù seeks
l+ the cost of sorting if relations are unsorted.
nhybrid merge-join: If one relation is sorted, and the other has a secondary B+-tree index on the join attribute
lMerge the sorted relation with the leaf entries of the B+-tree .
lSort the result on the addresses of the unsorted relation’s tuples
lScan the unsorted relation in physical address order and merge with previous result, to replace addresses by the actual tuples
4Sequential scan more efficient than random lookup
Hash-Join
nApplicable for equi-joins and natural joins.
nA hash function h is used to partition tuples of both relations
nh maps JoinAttrs values to {0, 1, ..., n}, where JoinAttrs denotes the common attributes of r and s used in the natural join.
lr0, r1, . . ., rn denote partitions of r tuples
4Each tuple trÎ r is put in partition ri where i = h(tr[JoinAttrs]).
lr0,, r1. . ., rn denotes partitions of s tuples
4Each tuple tsÎs is put in partition si, where i = h(ts[JoinAttrs]).
nNote: In book, ri is denoted as Hri, si is denoted as Hsi and nis denoted as nh.
nr tuples in rineed only to be compared with s tuples in si Need not be compared with s tuples in any other partition,since:
lan r tuple and an s tuple that satisfy the join condition will have the same value for the join attributes.
lIf that value is hashed to some value i, the r tuple has to be in riand the s tuple in si.
Hash-Join Algorithm
1. Partition the relation s using hashing function h. When partitioning a relation, one block of memory is reserved as the output buffer for each partition.
2. Partition r similarly.
3. For each i:
(a) Load si into memory and build an in-memory hash index on it using the join attribute. This hash index uses a different hash function than the earlier one h.
(b) Read the tuples in ri from the disk one by one. For each tuple tr locate each matching tuple tsin si using the in-memory hash index. Output the concatenation of their attributes.
nThe value n and the hash function h is chosen such that each si should fit in memory.
lTypically n is chosen as ébs/Mù * f where f is a “fudge factor”, typically around 1.2
lThe probe relation partitions si need not fit in memory
nRecursive partitioningrequired if number of partitions n is greater than number of pages M of memory.
linstead of partitioning n ways, use M – 1 partitions for s
lFurther partition the M – 1 partitions using a different hash function
lUse same partitioning method on r
lRarely required: e.g., recursive partitioning not needed for relations of 1GB or less with memory size of 2MB, with block size of 4KB.
Handling of Overflows
nPartitioning is said to be skewed if some partitions have significantly more tuples than some others
nHash-table overflow occurs in partition si if si does not fit in memory. Reasons could be
lMany tuples in s with same value for join attributes
lBad hash function
nOverflow resolution can be done in build phase
lPartition si is further partitioned using different hash function.
lPartition ri must be similarly partitioned.
nOverflow avoidance performs partitioning carefully to avoid overflows during build phase
lE.g. partition build relation into many partitions, then combine them
nBoth approaches fail with large numbers of duplicates
lFallback option: use block nested loops join on overflowed partitions
Cost of Hash-Join
nIf recursive partitioning is not required: cost of hash join is 3(br+ bs) +4 *nh block transfers + 2( ébr / bbù + ébs / bbù) seeks
nIf recursive partitioning required:
lnumber of passes required for partitioningbuild relation s is élogM–1(bs) – 1ù
lbest to choose the smaller relation as the build relation.
nUseful when memory sized are relatively large, and the build input is bigger than memory.
nMain feature of hybrid hash join:
Keep the first partition of the build relation in memory.
nE.g. With memory size of 25 blocks, depositor can be partitioned into five partitions, each of size 20 blocks.
l Division of memory:
4The first partition occupies 20 blocks of memory
41 block is used for input, and 1 block each for buffering the other 4 partitions.
ncustomer is similarly partitioned into five partitions each of size 80
lthe first is used right away for probing, instead of being written out
nCost of 3(80 + 320) + 20 +80 = 1300 block transfers for hybrid hash join, instead of 1500 with plain hash-join.
nHybrid hash-join most useful if M >>
Complex Joins
nJoin with a conjunctive condition:
r q1Ùq 2Ù... Ùqns
lEither use nested loops/block nested loops, or
lCompute the result of one of the simpler joins r qis
4final result comprises those tuples in the intermediate result that satisfy the remaining conditions
q1Ù . . . Ùqi –1Ùqi +1Ù . . . Ùqn
nJoin with a disjunctive condition
r q1 Úq2 Ú... Úqns
lEither use nested loops/block nested loops, or
l Compute as the union of the records in individual joins r q is:
(r q1s) È (r q2s) È . . . È (r qns)
Other Operations
nDuplicate elimination can be implemented via hashing or sorting.
lOn sorting duplicates will come adjacent to each other, and all but one set of duplicates can be deleted.
lOptimization: duplicates can be deleted during run generation as well as at intermediate merge steps in external sort-merge.
lHashing is similar – duplicates will come into the same bucket.
nProjection:
lperform projection on each tuple
lfollowed by duplicate elimination.
Other Operations : Aggregation
nAggregation can be implemented in a manner similar to duplicate elimination.
lSorting or hashing can be used to bring tuples in the same group together, and then the aggregate functions can be applied on each group.
lOptimization: combine tuples in the same group during run generation and intermediate merges, by computing partial aggregate values
4For count, min, max, sum: keep aggregate values on tuples found so far in the group.
–When combining partial aggregate for count, add up the aggregates
4For avg, keep sum and count, and divide sum by count at the end
Other Operations : Set Operations
nSet operations (È, Ç and ¾): can either use variant of merge-join after sorting, or variant of hash-join.
nE.g., Set operations using hashing:
lPartition both relations using the same hash function
lProcess each partition i as follows.
lUsing a different hashing function, build an in-memory hash index on ri.
lProcess si as follows
lr Ès:
lAdd tuples in si to the hash index if they are not already in it.
lAt end of si add the tuples in the hash index to the result.
lrÇs:
loutput tuples in sito the result if they are already there in the hash index
lr – s:
lfor each tuple in si, if it is there in the hash index, delete it from the index.
l At end of si add remaining tuples in the hash index to the result.
Other Operations : Outer Join
nOuter join can be computed either as
lA join followed by addition of null-padded non-participating tuples.
lby modifying the join algorithms.
nModifying merge join to compute r s
lIn r s, non participating tuples are those in r – PR(r s)
lModify merge-join to compute r s: During merging, for every tuple trfrom r that do not match any tuple in s, output tr padded with nulls.
lRight outer-join and full outer-join can be computed similarly.
nModifying hash join to compute r s
lIf r is probe relation, output non-matching r tuples padded with nulls
lIf r is build relation, when probing keep track of which r tuples matched s tuples. At end of si output non-matched r tuples padded with nulls
Evaluation of Expressions
nSo far: we have seen algorithms for individual operations
nAlternatives for evaluating an entire expression tree
lMaterialization: generate results of an expression whose inputs are relations or are already computed, materialize (store) it on disk. Repeat.
lPipelining: pass on tuples to parent operations even as an operation is being executed
nWe study above alternatives in more detail
Materialization
nMaterialized evaluation: evaluate one operation at a time, starting at the lowest-level. Use intermediate results materialized into temporary relations to evaluate next-level operations.
nE.g., in figure below, compute and store
then compute the store its join with customer, and finally compute the projections on customer-name.
nMaterialized evaluation is always applicable
nCost of writing results to disk and reading them back can be quite high
lOur cost formulas for operations ignore cost of writing results to disk, so
4Overall cost = Sum of costs of individual operations + cost of writing intermediate results to disk
nDouble buffering: use two output buffers for each operation, when one is full write it to disk while the other is getting filled
lAllows overlap of disk writes with computation and reduces execution time
Pipelining
nPipelined evaluation : evaluate several operations simultaneously, passing the results of one operation on to the next.
nE.g., in previous expression tree, don’t store result of
linstead, pass tuples directly to the join.. Similarly, don’t store result of join, pass tuples directly to projection.
nMuch cheaper than materialization: no need to store a temporary relation to disk.
nPipelining may not always be possible – e.g., sort, hash-join.
nFor pipelining to be effective, use evaluation algorithms that generate output tuples even as tuples are received for inputs to the operation.
nPipelines can be executed in two ways: demand driven and producer driven
nIn demand driven or lazyevaluation
lsystem repeatedly requests next tuple from top level operation
lEach operation requests next tuple from children operations as required, in order to output its next tuple
lIn between calls, operation has to maintain “state” so it knows what to return next
nIn producer-driven or eager pipelining
lOperators produce tuples eagerly and pass them up to their parents
4Buffer maintained between operators, child puts tuples in buffer, parent removes tuples from buffer
4if buffer is full, child waits till there is space in the buffer, and then generates more tuples
lSystem schedules operations that have space in output buffer and can process more input tuples
nAlternative name: pull and push models of pipelining
nImplementation of demand-driven pipelining
lEach operation is implemented as an iterator implementing the following operations
4open()
–E.g. file scan: initialize file scan
» state: pointer to beginning of file
–E.g.merge join: sort relations;
» state: pointers to beginning of sorted relations
4 next()
–E.g. for file scan: Output next tuple, and advance and store file pointer
–E.g. for merge join: continue with merge from earlier state till next output tuple is found. Save pointers as iterator state.
4close()
Evaluation Algorithms for Pipelining
nSome algorithms are not able to output results even as they get input tuples
lE.g. merge join, or hash join
lintermediate results written to disk and then read back
nAlgorithm variants to generate (at least some) results on the fly, as input tuples are read in
lE.g. hybrid hash join generates output tuples even as probe relation tuples in the in-memory partition (partition 0) are read in
lPipelined join technique: Hybrid hash join, modified to buffer partition 0 tuples of both relations in-memory, reading them as they become available, and output results of any matches between partition 0 tuples
4When a new r0 tuple is found, match it with existing s0 tuples, output matches, and save it in r0
No comments:
Post a Comment