Download Query Processing: Executor Operators and New Techniques - Prof. Amol V. Deshpande and more Study notes Database Management Systems (DBMS) in PDF only on Docsity!
CMSC724: Query Processing
Amol Deshpande
February 24, 2009
1 Query Processing
Query Processing
⢠Assume single-user, single-threaded
ā Concurrency managed by lower layers
⢠Steps:
ā Parsing: attritube references, syntax etc...
ā Catalog stored as ādenormalizedā tables
ā Rewriting:
ā Views, constants, logical rewrites (transitive predicates, true/false predicates), semantic (us-
ing constraints), subquery flattening
ā Optimizer ā Later
ā Executor: Next
1.1 Traditional Operators
Executor: Operators
⢠Selections: Usually pushed down if possible
ā SARGABLE predicates
ā Advantages in not doing so (for expensive predicates)
⢠Project
ā If no duplicate elimination, then trivial
ā If duplicate elimination, can use sorting (preferred) or hashing
ā Note that: this suggests that sort-merge joins may be preferable as the child operator
ā Decision made by the optimizer (āinteresting ordersā)
Executor: Operators
- Aggregates and Group by (usually together)
- Distributive (MAX, MIN, COUNT, SUM): Constant state
- Algebraic (AVERAGE): Can use COUNT and SUM
- Holistic (MEDIAN, QUANTILE): May need to gather the whole input
- PostgreSQL allows defining user-defined aggregates:
- User-defined Aggregates in PostgreSQL
- Basically need to define an āaccumulatorā function..
ā Take in one tuple at a time (get_next())
ā Eventually produce the aggregate (one by one)
Executor: Operators
- Joins
- Equijoin (natural join): Nested loops, Index nested loops, hash join (classic, GRACE, hybrid),
merge join
ā Sort-merge joins in some cases (e.g. ABS(R.a - S.b) < 5)
ā Index nested loops in some cases (e.g. index on R.a, may use for R.a < S.a)
ā Nested loops otherwise (always works)
- Join variants: Outerjoins, semijoins, Anti-joins etc...
ā Usually same algorithms as above, with minor modifications (may even be an "if" in the
code)
Executor: Operators
- Set operators: Intersection, Union, Difference etc..
- Variants of join operators (different logic based on duplicate eliminate or not)
- Note that: SQL is bag algebra
- Others?
- Top-K, CUBE etc...
- List goes on
Executor: Operators
- Much commonality between operators
- Usually a smaller set of Physical Operators
- e.g. TEMP is a materialization operator: Reads all tuples from the child operator and stores
them somewhere
ā by repeatadly issueing get_next()
- Similarly, HASH, SORT etc..
- See An overview of DB2 Optimizer for more details
1.2 New Operators
Query Processing
- Three new operators...
- (Binary) Symmetric Hash Join
- n-Ary Symmetric Hash Join (mJoin)
- Eddy
- Developed in parallel databases or streams contexts
- But useful in deterministic context as well
- Key difference between streams and disk-based
ā Iterators pull data (eventually from disk)
ā Streams push data into the query processor
ā Similarly, wide area data sources push data
- Parallel query processing has a combination
ā push (across processor) and pull (within a processor)
ā Volcano paper (later)
Query Processing: Symmetric Hash Join
- Produces results immediately ā Better time to first tuple
- Can implement as an iterator
- Alternate pulling data from the two children
R Hash Table
Build R Probe with S
S Hash Table
Build S Probe with R
RS Tuples
R
Build Probe
S
Build Probe
- Problems:
- Larger memory requirement
- Not as easy to extend to disk (XJoin)
n-Ary Symmetric Hash Join Operator (MJoin)
- For each relation: build a hash-table on each join attr.
- For each new tuple:
- insert it into appropriate hash table(s)
- probe into hash-tables on other relations
R
R.a
S
S.a S.b S,c
T
T.b
U
U.c
Tuple
Router
R S T U
MJoin Operator
SELECT *
FROM R, S, T, U
WHERE R.a = S. a
AND S.b = T.b
AND S.c = U. c
Example Query
T
S
R U
S
R
T U
S
T
U R
S
U
R T
Examples of Probing Sequences
n-Ary Symmetric Hash Join Operator (MJoin)
n-Ary Symmetric Hash Join Operator (MJoin)
- Intermediate tuples are never stored anywhere
- Need a policy for choosing the probing sequences
- Similarities to selection ordering
- Rank ordering: sort ascending by c/(1 ā p)
ā where c = cost of probing, p = selectivity
- Can change the probing sequence anytime w/o problems (adaptivity)
- Many more details in Survey on Adaptive QP
- Issues:
- Typically less efficient than a tree of binary joins
- Iterator?
- Can alternate pulling from different children
Count
Eddy
select count(*)
from R, S, T
where R.a = S.a and S.b = T.b
and pred(R.c)
Scan(R) Scan(S) Scan(T)
select *
from R, S, T
where R.a = S.a and S.b = T.b
and pred(R.c)
Figure 2: Using traditional operators along with an eddy
Creating a Plan with Eddyās
The PostgreSQL plan creation routine starts by identi-
fying query blocks that consist of only selects, projects,
and joins. It then calls the postgres cost-based optimizer
to choose and construct an execution plan for each such
block. It also instantiates operators for handling the rest
of the SQL constructs such as aggregates and group-bys,
that are then put together with the execution plans for the
query blocks to obtain an execution plan for the entire
query. To be able to use eddies, we modified the plan
creation routine so that, instead of calling the optimizer,
it creates an eddy operator directly for each query block
(as discussed above, such a query block is exactly what a
single eddy operator can handle as well). These eddy op-
erators are then put together with operators instantiated
for handling aggregations and group-bys as before, to get
an execution plan for the entire query.
In addition, to set up each select-project-join query
block with an eddy, the plan creation routine instantiates
a set of operators as follows :
- For each data source in the query (these may be base
relations, streams or subqueries), a Scan operator is
instantiated. The eddy interacts with these operators
using the iterator interface, and as such, the exact
nature of these operators is not relevant.
- For each expensive predicate in the query, the parser
instantiates a selection operator. Predicates without
expensive methods are attached to operators as in
traditional PostgreSQL.
- For each join in the query, either a symmetric hash
join operator or an index join operator is instanti-
Scan(R) Sc
Hash Table on R.a
Hash Table on S.a
SHJ on R.a = S.a
Ed
Figure 3: Eddy inst
tuples. The routing a
possible operators that
be routed to, where the
be the sources it consi
ready passed through.
of a tuple is stored in th
tuple itself. We use the
rays in order to quickly
given signature can be
natures (or bitmaps) is
this approach is not su
relations.
Query Processing
To support the iterator
to remember the comp
turned the last tuple. T
a stack of active opera
active if they have an o
discuss below, selectio
during query execution
When an upstream
eration on the eddy,
steps :
- If there are any a
empty), call get n
the stack.
the stack, an
Eddy/Tuple Router: Mechanism vs Policy
- Tricky to reason about: Encapsulates too much logic
- Break into two pieces (discussion from AQP Survey )
- Mechanism: Enables the adaptivity
- By allowing eddy choice at any point
- As long as the eddy obeys some rules, the execution will be correct
ā Not always easy... arbitrary routings can be nonsensical
- For any tuple, the mechanism tells the eddy the valid set of operators to route to
- Mechanism can be implemented efficiently (see SIGMOD Record paper)
- Policy: Exploit the adaptivity
- For each tuple, choose the operator to route too
- This can be as complex as you want
Eddy/Tuple Router: Steps
- Instatiate operators based on the query
- Fully pipelined operators (SHJ, MJoins) preferred, otherwise not as much feedback
- Sort-merge join will not provide any output tuples till all input tuples are consumed
- At each instance:
- Choose next tuple to process
ā Either a new source tuple or an intermediate tuple produced by an operator
- Decide which operator to route to (using the policy)
Count Eddy n(R) Scan(S) Scan(T) select * from R, S, T where R.a = S.a and S.b = T.b and pred(R.c) l operators along with an eddy dyās eation routine starts by identi- onsist of only selects, projects, postgres cost-based optimizer n execution plan for each such operators for handling the rest h as aggregates and group-bys, with the execution plans for the n execution plan for the entire eddies, we modified the plan nstead of calling the optimizer, r directly for each query block a query block is exactly what a andle as well). These eddy op- her with operators instantiated and group-bys as before, to get entire query. each select-project-join query an creation routine instantiates ws : in the query (these may be base subqueries), a Scan operator is y interacts with these operators terface, and as such, the exact tors is not relevant. redicate in the query, the parser n operator. Predicates without are attached to operators as in L. query, either a symmetric hash index join operator is instanti- ments here, we let the postgres join algorithm, and ensure that s are the same when comparing . rators instantiated by the query Scan(R) Scan(S) Scan(T) Selection Operator pred(R.c)
Hash
Table on R.a Hash Table on S.a
SHJ on R.a = S.a SHJ on S.b = T.b
Hash
Table on S.b Hash Table on T.b
Eddy Figure 3: Eddy instantiated for the example query tuples. The routing arrays essentially maintain all the possible operators that a tuple of a given signature may be routed to, where the signature of a tuple is defined to be the sources it consists of and the operators it has al- ready passed through. As suggested in [2], the signature of a tuple is stored in the form of a bitmap along with the tuple itself. We use these bitmaps to index the routing ar- rays in order to quickly find all the operators a tuple of a given signature can be routed to. The number of such sig- natures (or bitmaps) is usually exponential, and as such, this approach is not suitable for queries with very many relations. Query Processing To support the iterator model interface, the eddy needs to remember the computational state it was in when it re- turned the last tuple. The eddy does this by maintaining a stack of active operators. The join operators are called active if they have an outstanding probe tuple; as we will discuss below, selection operators are treated differently during query execution. When an upstream operator performs a get next() op- eration on the eddy, the eddy performs the following steps :
- If there are any active operators (if the stack is not
empty), call get next() on the operator on the top of the stack.
- If the call returns a null , pop the operator off
the stack, and repeat Step 1.
- If the get next() call returns a tuple, proceed to
Step 3.
- If there are no active operators, choose a source
from the list of input sources and use get next() to fetch a new source tuple. If none of the sources have
- Add result tuples from the operator (if any) to a queue
ā If a result tuple is fully processed, send to output
- We will revisit policy issues when discussing AQP
2 Query Optimization
Query Optimization
- Goal: Given a SQL query, find the best physical operator tree to execute the query
- Problems:
ā More importantly, cheapest plan orders of magnitude cheaper than worst plans
ā Typical compromise: avoid really bad plans
- Complex operators/semantics etc
ā (R outerjoin S) join T 6 = R outerjoin (S join T)
Query Optimization
- Heuristical approaches
- Perform selection early (reduce number of tuples)
- Perform projection early (reduce number of attributes)
- Perform most restrictive selection and join operations before other similar operations.
- Donāt do Cartesian products
- Formulas for computing the costs
- An enumeration algorithm to search through the plan space
- Dynamic programming
Aside...
- Cost metric
- Typically a combination of CPU and I/O costs
ā The "w" parameter set to balance the two
- Response time (useful in distributed and parallel scenarios)
ā Behaves different from the above total work metric
- Time to first tuple (useful in interactive applications)
- How about a simpler metric?
- Count the total number of intermediate tuples that would be generated
- Independent of access methods
- Ok in some scenarios, but reasoning about indexes is key in optimization
System-R Query Optimizer
- Dynamic programming
- Uses āprinciple of optimalityā
- Bottom-up algorithm
- Compute the optimal plan(s) for each k-way join, k = 1, ..., n
ā Only O(
n
) instead of O(n!)
- Computes plans for different āinteresting ordersā
ā Extended to āphysical propertiesā later
- Another way to look at it:
ā Plans are not comparable if they produce results in different orders
ā An instance of multi-criteria optimization
Since then...
- Search space
- āBushyā plans (especially useful for parallelization)
- Cartesian products (star queries in data warehouses)
- Algebraic transformations
ā Can āgroup byā and ājoinā commute?
ā Hash joins, semi-joins (crucial for distributed systems)
- Sub-query flattening, merging views
ā āQuery rewriteā
- Parallel/distributed scenarios...
Since then...
- Statistics and cost estimation
- Optimization only as good as cost estimates
ā Optimizers not overly sensitive (± 50% probably okay)
ā Better to overestimate selectivities
- Histograms, sampling commonly used
- Correlations?
ā Ex: where model = āaccordā and make = āhondaā
ā Say both have selectivities 0.
ā Then combined selectivity is also 0.0001, not 0.
- Learning from previous executions
ā Learning optimizer (LEO@IBM), SITS (MS SQL Server)
- Cost metric: Response time in parallel databases, buffer utilization...
Since then...
ā Easier to implement, low memory footprint
- Top-down (Volcano/Cascades/SQL Server)
ā More extensible, typically larger memory footprint etc...
- Neither work for large number of tables
ā Randomized, genetic etc...
ā More common to use heuristics instead
- āParametric query optimizationā
Other issues
- Non-centralized environments
- Distributed/parallel, P2P
- Data streams, web services
- Sensor networks??
- User-defined functions
- Materialized views
AQP: Overview/Summary
- Low-overhead, evolutionary approaches
- Typically apply to non-pipelined execution
- Late binding: Donāt instatntiate the entire plan at start
- Mid-query reoptimization: At āmaterializationā points, review the remaining plan and possi-
bly re-optimize
ā More recently, much work/implementation along these lines at IBM
- Pipelined execution
- No materialization points, so the above doesnāt apply
- The operators may contain complex states, raising correctness issues
- Eddies
ā Always guarantee correct execution, but allows reordering during execution
- Much other work in recent years (see the survey, or slides on the webpage)
4 Data Streams
4.1 Motivation
Data Streams
- Why?
- Much data generated continuously (growing every day)
- Financial data
- Sensors, RFID
- Network/systems monitoring
- Video/Audio data
- etc ...
- Need to support:
- High data rates
- Real-time processing with low latencies
- Support for temporal reasoning (time-series operations)
- Data dissemination
- Distributed? (at least data generation)
- etc...
Examples of Tasks
- Continuous (SQL) queries
- E.g. moving average over last hour every 10 mins
- SQL extended to support āwindowsā over streams
- Proposed extensions: SEQUENCE, CQL, StreamSQL
- Pattern recognition
- Alert me when: A, then B within 10 mins
- How to specify? StreamSQL has some support
- Probabilistic modeling; Applying financial models
- Infer hidden variables
- Remove noise (from measured readings)
- Do complex analysis to decide whether to buy
- We donāt even know how to specify these
- Multimedia data?
- Online object detection, activity detection
- Correlating events from different streams
Data Streams
- Use traditional DBMS?
- Consider simplest case:
- Report moving average over last hour every 10 minutes
- Insert all new items into database
- Execute the query every 10 minutes
- Not easily generalizable to other tasks
- E.g. āalert me the moment moving average > 100ā?
- Typically 1000ās of such continuous queries
- Even for one query, too slow and inefficient
- Doesnāt reuse work from previous execution
- Application-level modules typically used for complex tasks
http://www.enterprisedb.com/documentation/trigger-examples.html Page 1 of 5 The message, New employees are about to be added, is displayed once by the firing of the trigger even though the result is the addition of three new rows. 15.6.2. After Statement-Level Trigger The following is an example of an after statement-level trigger. Whenever an insert, update, or delete operation occurs on the emp table, a row is added to the empauditlog table recording the date, user, and action. CREATE TABLE empauditlog ( audit_date DATE, audit_user VARCHAR 2 ( 20 ), Trigger Examples 03/29/2007 10:08 AM http://www.enterprisedb.com/documentation/trigger-examples.html Page 2 of 5 audit_user VARCHAR 2 ( 20 ), audit_desc VARCHAR 2 ( 20 ) ); CREATE OR REPLACE TRIGGER emp_audit_trig AFTER INSERT OR UPDATE OR DELETE ON emp DECLARE v_action VARCHAR 2 ( 20 ); BEGIN IF INSERTING THEN v_action := 'Added employee(s)'; ELSIF UPDATING THEN v_action := 'Updated employee(s)'; ELSIF DELETING THEN v_action := 'Deleted employee(s)'; END IF; INSERT INTO empauditlog VALUES (SYSDATE, USER, v_action); END; In the following sequence of commands, two rows are inserted into the emp table using two INSERT commands. The sal and comm columns of both rows are updated with one UPDATE command. Finally, both rows are deleted with one DELETE command. INSERT INTO emp VALUES ( 9001 ,'SMITH','ANALYST', 7782 ,SYSDATE,NULL,NULL, 10 ); INSERT INTO emp VALUES ( 9002 ,'JONES','CLERK', 7782 ,SYSDATE,NULL,NULL, 10 ); UPDATE emp SET sal = 4000. 00 , comm = 1200. 00 WHERE empno IN ( 9001 , 9002 ); DELETE FROM emp WHERE empno IN ( 9001 , 9002 );
SELECT TO_CHAR(AUDIT_DATE,'DD-MON-YY HH 24 :MI:SS') AS "AUDIT DATE",
audit_user, audit_desc FROM empauditlog ORDER BY 1 ASC;
AUDIT DATE AUDIT_USER AUDIT_DESC
31 - MAR- 05 14 : 59 : 48 SYSTEM Added employee(s) 31 - MAR- 05 15 : 00 : 07 SYSTEM Added employee(s) 31 - MAR- 05 15 : 00 : 19 SYSTEM Updated employee(s) 31 - MAR- 05 15 : 00 : 34 SYSTEM Deleted employee(s) The contents of the empauditlog table show how many times the trigger was fired - once each for the two inserts, once for the update (even though two rows were changed) and once for the deletion (even though two rows were deleted). 15.6.3. Before Row-Level Trigger The following example is a before row-level trigger that calculates the commission of every new employee belonging to department 30 that is inserted into the emp table. CREATE OR REPLACE TRIGGER emp_comm_trig BEFORE INSERT ON emp FOR EACH ROW BEGIN IF :NEW.deptno = 30 THEN :NEW.comm := :NEW.sal *. 4 ; END IF; END;
Figure 2: Trigger Example (Hansen et al.)
er set. from , ify the having 3], can regates an be e-table from a ed, is salary = erMan ainst a the do es, the allows ore an n are macro tion is command used in the rule action is a special command that allows rule actions to communicate with the outside world [Hans98].
3. System Architecture
The TriggerMan architecture is made up of the
following components:
- the TriggerMan DataBlade which lives inside of Informix,
- data sources , which normally correspond to local or remote tables. Most commonly, a data source will be a local table. In that case, standard Informix triggers are created automatically by TriggerMan to capture updates to the table. We use the one trigger per table per update event available in Informix to capture updates and transmit them to TriggerMan by inserting Host DBMS: Informix with Universal Data Option TriggerMan DataBlade TriggerMan Console ...
Update Queue Table Update Queue in Shared Memory
TriggerMan
Client App Data Source App Data Source App ... TriggerMan Client App TriggerMan Driver ...
Data Source Trigger
Figure 1. The architecture of the TriggerMan
trigger processor. Figure 3: Triggerman (Hansen et al.) Triggerman Triggerman Triggers ⢠Precursor to data streams work ⢠Event-driven as opposed to query driven ⢠Can handle pub-sub applications well ⢠Can identify quickly queries that should be executed ⢠But, no discussion on how to execute those queries efficiently ā E.g. āmoving averageā query
nd an edge for odes contain a for that node, he edges each on for the join
. Groups of
les or three or special ācatch h. These will tely, they will ere to simplify le. alpha node in seen before by atures in the urce on which e 3). If no as been seen to the list and atalog table. one constant t table for the tants in it, add the expression egies for s at contains at e one or more at belong to small or large. nge of sizes of r a particular strategies are low overhead class is small. r non-indexed alence class is red to organize ās equivalence ed to make it s of triggers same signature but different constants -- they are mandatory in a scalable trigger system. Strategies 1 and 2 are also required in order to make the common case (a few thousand triggers or less) fast. A cost model that illustrates the tradeoffs is presented in [Hans98b]. Strategies 1 and 2 have been implemented in TriggerMan and strategies 3 and 4 are under construction. 5.3. Common Sub-expression Elimination for Selection Predicates An important performance enhancement to reduce the total time needed to determine which selection predicates match a token is common sub-expression elimination. This can be achieved by normalizing the predicate index structure. Figure 4 shows an expanded view of the predicate index given in Figure 3. The constant set of an expression signature contains one element for each constant (or tuple of constants [const1, ⦠,constK]) occurring in some selection predicate that matches the signature. Each constant is linked to a triggerID set, which is a set of the ID numbers of triggers containing a particular selection predicate. For example, if there are rules of the form: create trigger T_I from R when R.a = 100 do ⦠for I=1 to N, then there will be an expression signature R.a=CONSTANT, the constant set for this signature will contain an entry 100, and the triggerID set for 100 will contain the ID numbers of T_1 ⦠T_N. We will implement constant sets and triggerID sets in a fully normalized form, as shown in Figure 4, when these sets are stored as either main memory lists or indexes (organizations 1 and 2). This normalized main-memory data structure will be built using the data retrieved from the constant table for the expression signature.
data source^ predicate index root
predicate indexes ⦠⦠⦠expression ⦠⦠⦠signature list ⦠⦠constant set (set of unique constants) ⦠triggerID set (set of IDs of different triggers having same set of constants)
Figure 4. Expanded View of Normalized
Predicate Index Structure. Figure 4: Triggerman (Hansen et al.)
ā Every new tuple will satisfy the query ā Trigger action (compute moving avg) will be invoked per new tuple
- No sharing of work from previous execution
- No sharing of work between multiple triggers
ā E.g. If one person wants moving average over last hour, other person over last two hours
4.3 Major Concepts
Data Streams: Some Major Concepts
- New non-blocking operators
- Symmetric hash join, MJoin, XJoin, Eddy etc...
- Adaptivity
- Dealing with unpredictability
- Sharing/Multi-query optimization
- 1000ās of queries; must share execution
- Load shedding
- Bursty data: Too much to handle at some times
- Declarative languages
- Especially for pattern recognition, modeling etc
- Theoretical developments
- āOne-passā algorithms
- For exact or approximate computation
- Examples:
- Average: O(1) (number of entries, total sum)
- Median:
ā Exact: Space complexity = N
ā Approximate: O(
1
log
2
N ), with error
FM-Sketches
- Flajolet-Martin Sketch: Count distinct number of values in a sequence in one pass with minimum
memory
- N = Length of the sequence
- n = Number of distinct values
- Naive Approach:
- Keep a list of all distinct values, and update incrementally
- O(n)
- FM-Sketches: Approximate counting in O(log(n)) space
FM-Sketches
- Algorithm:
- Use a bitmap, B, of size k, where k is ā Īø(log 2 (n))
ā Arenāt we trying to estimate n?
ā Use a rough upper bound. Even if you overestimate by a factor of 4, you only use 2 more
bits.
- Need a uniform hash function: h(x) maps values in the sequence to { 0 , Ā· Ā· Ā· , 2 k^ ā 1 }.
- For each value, v in the sequence, find h(v).
- Let l(h(v)) denote the least-significant 1 bit in h(v).
ā k = 6, h(v) = 000100, then l(v) = 3.
ā k = 6, h(v) = 000101, then l(v) = 1.
- Set B(l(v)) = 1.
- Note: Duplicate values will just set the same bit again: āduplicate-insensitiveā
FM-Sketches
- Algorithm (Cntd):
- At the end, let c be the least-significant (right-most) 0 in B
- 2928 Ć 2
c
is an estimator for the number of distinct values
ā Choose a number, x, uniformly between 0 to 2
k
ā P rob(l(x) = c) = 1/ 2
c+
ā Hash function is assumed to map values in the sequence uniformly onto the above range as
well
- Use multiple hash functions for more confidence
- Space: O(log(n))
- Choosing hash functions?
ā Tricky: uniform hash functions take a lot of space
ā Much work on relaxing the requirement
AMS Sketches
- Alon, Matias, Szegedy: Space Complexity of Approximating the Frequency Moments; STOC 1996
- Consider a stream: (1, 2, 3, 1, 5, 2, 1, 3, 4)
- Let mi be the frequency of i in the stream
- m 1 = 3, m 2 = m 3 = 2, m 4 = m 5 = 1.
- Frequency moment Fk = Σ
n
i=1m
k i
- F 0 = 5 = number of distinct elements in the stream
- F 1 = 9 = total number of elements in the stream
- F 2 = 19 = comes in up many places (e.g. self-join size of a relation)
- How to compute?
- Exact computation: O(n), where n is the number of distinct elements, not the size of stream
- Approximate: AMS Result: Can approximate F 0 , F 1 , F 2 in logarithmic space, requires O(n
Ī©(1)
space for others