Presentation is loading. Please wait.

Presentation is loading. Please wait.

Ján GENČI PDT 2009 Systém riadenia bázy dát (Database Management System)

Similar presentations


Presentation on theme: "Ján GENČI PDT 2009 Systém riadenia bázy dát (Database Management System)"— Presentation transcript:

1 Ján GENČI PDT 2009 Systém riadenia bázy dát (Database Management System)

2 2 Obsah RAID 2-phase multiway sort-merge Fyzická organizácia dát Indexovanie Systémový katalóg Operácie relačnej algebry (krátko) Implementácia operácií relačnej algebry Query plány – optimalizácia dotazov

3 3 Literatúra [1] Hector Garcia-Molina, Jeffrey D. Ullman, Jennifer D. Widom: Database System Implementation, Prentice Hall, 1999. ISBN-10: 0130402648, pp.653 Database Systems: The Complete Book, 2001

4 4 Literatúra [2] Elmasri R., Navathe S. B. : Fundamentals of database systems. 4th ed., Pearson Education, 2001. 5th ed. – 2006, pp. 1030 (ch. 13-15 -19; 120 resp. 220 str.)

5 5 Literatúra [3] Ramakrishnan R., Gehrke J.: Database Management Systems. McGraw-Hill Science/Engineering/Math; 3rd ed., 2002, pp. 906 (ch. 7-14; 220 str.)

6 6 Literatúra [4] Abraham Silberschatz, Henry Korth, S. Sudarshan: Database System Concepts. McGraw-Hill Science/Engineering/Math; 5th ed., 2005. pp.~920 (ch. 11-14-17; 170 resp. 290 str.

7 RAID Obrázky (väčšina) z [2]

8 8 RAID Originally - Redundant Arrays of Inexpensive Disks. Currently - Redundant Array of Independent Disks Chen, Lee, Gibson, Katz, and Patterson (1994), ACM Computing Survey, Vol. 26, No.2 (June 1994). http://sk.wikipedia.org/wiki/RAID (pekne názorne spracované)

9 9 RAID 0

10 10 RAID 1, 2

11 11 RAID 3, 4, 5, 6

12 12 RAID – ďalšie kombinácie 10, 01 - Kombinácie základných RAIDov Performance: –Block-interleaved distributed-parity disk arrays (RAID 5) have the best small read, large read, and large write performance of any redundant disk array. –Small write requests are somewhat inefficient compared with redundancy schemes such as mirroring.

13 Two phase, multiway sort-merge Na základe prezentácie Simonas Šaltenis: Advanced Algorithm Design and Analysis

14 14 Purpose of Algorithm Triedenie veľkých súborov dát (Data>Memory) Klasický algoritmus – Wirthov sort-merge algoritmus (Wirth C.: Algoritmy a dátové štruktúry.)

15 15 Princíp – 1. fáza 1.Vytvoriť maximálne možné veľké „behy“ (utriedené postupnosti elementov) – najlepšie načítaním do dostupnej pamäte a zotriedením napr. quick-sortom 2.Spájanie behov (mergovanie)

16 16 Princíp – 2. fáza File Y: File X: Run 1 Run 2 Current page EOF Bf1 p1 Bf2 p2 Bfo po min(Bf1[p1], Bf2[p2], …, Bfk[pk]) Read, when pi = B Write, when Bfo full Run k=n/m Current page Bfk pk

17 17 Zhodnotenie Fáza 1: O(n), Fáza 2: O(n) Celkom: O(n) I/Os! Dajú sa triediť iba súbory obmedzenej veľkosti –Fáza 2 môže spájať (merge) maximálne m-1 behov (m – počet vyrovnávacích pamätí). –Čo znamená: N/M (počet behov) ≤ m-1

18 18 Triedenie veľmi veľkých súborov (m-1) 2 M (m-1) 3 M = N Phase 2 Phase 1 … MM (m-1)M MM M M … MM MM M M … MM MM M M … … …...

19 19 Otázky

20 SRBD – štruktúry a algoritmy

21 21 Zdroj [1]

22 Primárne (fyzické) organizácie

23 23 Zdroj:Paul Beynon-Davies: DATABASE SYSTEMS.3RD ED. PALGRAVE MACMILLAN,2004

24 24 O čom budeme hovoriť Podporované dátové typy Formovanie záznamov Organizácia (radenie) záznamov –fyzická –logická „Umiestnenie“ DBMS v rámci OS

25 25 Podporované dátové typy Tzv. built-in dátové typy Pre účely ukladania dát, je pre nás zaujímavá veľkosť dátového typu (sizeof(typ)) „Sémantika“ typu je podporená implementáciou (HW alebo SW) relevantných operácií (out of scope)

26 26 Formáty ukladaných záznamov Záznamy s pevnou dĺžkou (A fixed-length record) Záznamy s premenlivou dĺžkou (A record with variable-length fields) Záznamy s premenlivou dĺžkou s oddelľovačmi (A variable-field record with separator characters).

27 27 Storage Record Formats [2]

28 28 Fixed length record Veľkosť záznamu je uložená v systémovom katalógu

29 29 Variable length records Záznamy s premenlivou dĺžkou

30 30 Reprezentácia NULL hodnôt Prakticky väčšina zdrojov o spôsobe implementácie „mlčí“ Pri záznamoch premenlivej dĺžky sa dá využiť null pointer na prvok záznamu ORACLE v dokumentácii pre ORA7 prezentoval ukladanie NULL hodnoty cez bitmapový prefix záznamu

31 31 Fyzická organizácia záznamov

32 32 Fyzická organizácia záznamov 2

33 33 Umiestňovanie záznamov do fyzických blokov Spanned Unspanned

34 34 Logické organizácie záznamov Sekvenčná Hašovaná Heap (hromada) Zhodnotenie z pohľadu operácií insert, find a delete

35 35 Sekvenčná organizácia

36 36 Zhodnotenie – sekvenčná org. Insert – drahá operácia (potreba posunúť priemerne N/2 záznamov) – oblasti pretečenia (overflow areas) Find – možnosť binárneho vyhľadávania podľa usporiadavajúceho atribútu - O(log 2 N), ináč O(N) = N/2 alebo N Delete – drahá operácia (potreba posunúť priemerne N/2 záznamov) – možnosť označovať záznamy ako zmazané  pack

37 37 Interné Hašovanie

38 38 Zhodnotenie – hašovanie Insert – O(1) ak neuvažujeme konflikty; ak uvažujeme - najhorší prípad O(N) Find – O(1) – hashovací atribút, O(N) ostatné atribúty Delete – O(1) Štruktúra musí byť dimenzovaná na maximálny počet záznamov

39 39 Externé hašovanie

40 40 Zhodnotenie - externé hašovanie Ako interné hašovanie Konflikty sa riešia blokmi pretečenia (viď ďalší slajd )

41 41 Ext. hašovanie –bloky pretečenia

42 42 „Rozšíriteľné“ hašovanie

43 43 Zhodnotenie – rozšíriteľné hašovanie Ako externé hašovanie Plusom je možnosť dynamického rozširovania „veľkosti hašovacieho poľa“

44 44 Heap (hromada) Záznamy sú neusporiadané – nie je usporiadavací atrubút Strácame možnosť - binárne vyhľadávanie; primárny index (ale iba pre usporiad. atr.) Veľmi efektívna operácia INSERT

45 45 Miesto DBMS v rámci OS Cooked files Raw devices NTFS DBMS Služby OS Filesystem Driver DBMS Služby OS - Driver

46 46 Otázky

47 Indexovanie Z podstatnej časti podľa [2] Všetky obrázky z [2]

48 48 Index Alternatívny spôsob prístupu k dátam Lokalizácia záznamu podľa obsahu

49 49 Kategorizácia indexov Počet úrovní Kategorizácia indexov Indexované záznamy Indexovaný atribút Hustý Riedky Primárne Viacúrovňové Jednoúrovňové Sekundárne Klastrovacie

50 50 Kategorizácia indexov Podľa počtu úrovní: –Jedno-úrovňové –Viac-úrovňové Podľa indexovaného atribútu: –Primárne –Klastrovacie (clustering) –Sekundárne Podľa počtu indexovaných záznamov: –Hustý (dense) – všetky záznamy v indexe –Riedky (sparse) – len časť záznamov v indexe

51 51 Jednoúrovňové indexy

52 52 Primárny index Indexuje „usporiadavajúci“ (ordering) atribút Riedky (sparse) index „Kotviaci“ záznam INSERT problém

53 53 Clustering index Aj nad „neusporia- davajúcim“ atribú- tom Primárna organizá- cia sa usporiada podľa daného atri- bútu – pri budovaní indexu

54 54 Clustering index Pri bežnej práci sa primárna organizácia nemodifikuje, ale používajú sa bloky pretečenia (overflow)

55 55 Sekundárny index Index nad neusporiada- vajúcim atribútom (ale kľúčovým) Hustý (dense) index

56 56 Sekundárny index Nad nekľúčovým atribútom (opakujúce sa hodnoty)

57 57 Priebežné zhodnotenie Zatiaľ iba jednoúrovňové indexy Prínos ( N – počet záznamov, r – záznamov v bloku) –Vyhľadávanie nad „ordered“ kľúčom – log 2 N –Vyhľadávanie nad „non-ordered“ kľúčom – N/2 –Vyhľadávanie nad nekľúčovým atribútom – N –Primárny index log 2 (N/r) –Sekundárny index log 2 N (počet čítaných blokov – podstatne menší, kvôli vyššiemu blokovaciemu faktoru)

58 58 Príklad – sekvenčný súbor (ordering attribute) Ordered file with r = 30,000 records Block size B = 1024 bytes. Records are of fixed size and are unspanned Record length R = 100 bytes. The blocking factor bfr = floor(B/R) = floor(1024/100) = 10 records per block. The number of blocks b = (r/bfr) = r (30,000/1O)l = 3000 blocks. A binary search would need approximately –floor(log 2 b) = floor(log 2 3000) = 12 block accesses.

59 59 Primárny index Na osvieženie pamäti

60 60 Príklad – primárny index Key field of the file is V = 9 bytes long, a block pointer is P = 6 bytes size of index entry R = (9 + 6) = 15 bytes,  blocking factor bfr i = floor(B/R i ) = floor(1024/15) = 68 entries per block. The total number of index entries r i is equal to the number of blocks in the data file - 3000. The number of index blocks is hence b i = ceiling(r/bfr i ) = ceiling(3000/68) = 45 blocks. To perform a binary search on the index file would need ceiling (log 2 b i )l = ceiling (log 2 45) = 6 (block accesses). To search for a record using the index, we need one additional block access to the data file - total of 6 + 1 = 7 block accesses

61 61 Príklad – sekundárny index As example 1: r = 30,000,R = 100 bytes, B = 1024 bytes. To do a linear search, we would require b/2 = 3000/2 = 1500 block accesses (on the average, 3000 in the worst case) Supppose V = 9 and P = 6  bfr i = 68 –secondary index is dense  the total number of index entries r i is equal to the number of records = 30,000. –The number of blocks needed for the index is b i = ceiling(r/bfr) = 1(30,000/68) l = 442 blocks. –A binary search on this secondary index needs ceiling(log 2 b i ) = ceiling (log 2 442) = 9 block accesses.

62 62 Porovnanie (single-level) indexov

63 63 Viacúrovňové indexy (Multi-Level Indexes)

64 64 Viacúrovňové indexy Vzhľadom na to, že jednoúrovňový index je „usporiadaným“ súborom (ordered file), môžeme vytvoriť primárny index nad indexom samotným; v tomto prípade originálny indexový súbor sa nazýva indexom prvej úrovne (first-level index) a index nad indexom sa nazýva indexom druhej úrovne (second-level index). Proces môžeme opakovať, vytvárajúc tretiu, štvrtú,..., najvyššiu úroveň dovtedy, kým najvyššia úroveň nezaberá jediný blok na disku Viac úrovňový index môže byť vytvorený pre akýkoľvek typ indexu prvej úrovne (primary, secondary, clustering) za predpokladu, že index prvej úrovne zaberá viac ako jeden diskový blok

65 65 Viacúrovňové indexy Prvá úroveň - dense alebo sparse Ďalšie úrovne už iba sparse Top level – iba jeden blok Vyhľadávanie vyžaduje pribl. (log bfri b i ) „block accesses“ INSERT problém !!!

66 66 Dynamické viacúroňové indexy na báze B- Trees a B+-Trees Kvôli problémom so zaraďovaním a vyraďovaním záznamov, vačšina viacúrovňových indexov používa B- tree or B+-tree Tieto štruktúry umožňujú efektívne vykonávanie vkladaní a mazaní nových hodnôt (search values). V B-Tree a B+-Tree, každý uzol stromu zodpovedá diskovému bloku Každý uzol je udržiavaný zaplnený na viac ako polovicu

67 67 Dynamické viacúroňové indexy na báze B- Trees a B+-Trees (pokr.) Vkladanie do uzla, ktorý nie je úplne zaplnený je veľmi efektívne; ak je uzol plný, operácia vkladanie spôsobí rozdelenie uzla do dvoch uzlov (pôvodný a nový) Rozdeľovanie sa môže šíriť do ďalších úrovní stromu Mazanie je opäť relatívne efektívne, kým uzol „nepodtečie“ pod polovicu Ak dôjde k podtečeniu pri mazaní, uzol musí byť spojený so susednými uzlami (hrozí „kolaps“ úrovne)

68 68 Rozdiely medzi B-tree a B+-tree V B-tree, odkazy (pointers) na dátové záznamy sú uložené vo všetkých uzloch stromu (na všetkých úrovniach) V B+-tree, odkazy (pointers) na dátové záznamy sú uložené iba v listových uzloch stromu B+-tree môže mať menej úrovní (alebo väčšiu „kapacitu“) než zodpovedajúci B-tree

69 69 Štruktúra B-tree

70 70 Štruktúra B+-tree

71 71 B+-tree príklad

72 72 B-tree príklad – zopár čísel [2]

73 73 B+-tree príklad - zopár čísel [2]

74 74 B-tree – duplicate keys

75 75 Otázky

76 Systémový katalóg Na základe prezentácie Ľubomíra Miškoviča

77 77 Čo je systémový katalóg Systémový katalóg uchováva dáta ktoré popisujú každú databázu (metadata) Obsahuje popis: –Položiek, viet, súborov a vzťahov medzi nimi –Konceptuálnej schémy, externých schém a internú schému. Je tu popísané aj mapovanie medzi schémami na rôznych úrovniach

78 78 Zjednodušený model prostredia databázového systému

79 79 Obsah systémového katalógu Katalógy pre relačné SRBD obsahujú –Názvy relácií –Názvy atribútov –Domény atribútov –Primárne kľúče –Sekundárne kľúčové atribúty –Cudzie kľúče –Podmienky

80 80 Obsah systémového katalógu Ďalej obsahujú popisy –Externých pohľadov –Uloženie štruktúr a indexov pre internú úroveň –Informácie o bezpečnosti a autorizácií, ktoré definujú prístup používateľa k databázovým pohľadom –Prihlasovacie mená tvorcov alebo vlastníkov každej relácie

81 81 Obsah systémového katalógu Uchovávajú informácie ako –Veľkosť záznamu –Aktuálny počet záznamov –Počet indexov –Meno tvorcu každej relácie

82 82 Spôsoby implementácie systémového katalógu Systémový katalóg môže byť vytváraný pre každú databázu v systéme, alebo môže byť spoločný pre všetky databázy Systémový katalóg môže byť tvorený tabuľkami, ktorých štruktúra je totožná s tabuľkou databázy alebo špeciálnou štruktúrou

83 83 Príklad systémových katalógov pre Informix Systables – opisuje každú tabuľku v databáze. Obsahuje jeden riadok pre každú tabuľku v databáze, pohľad alebo synonymum definované v databáze. Zahŕňa všetky tabuľky v databáze aj tabuľku systémového katalógu Syscolumns – definuje každý stĺpec v databáze. Pre každý stĺpec definovaný v tabuľke alebo pohľade existuje jeden riadok Sysindex – popisuje indexy v databáze. Obsahuje jeden riadok pre každý index definovaný v databáze

84 84 Systables

85 85 syscolumns

86 86 Vzťah medzi tabuľkami

87 87 Oracle

88 88 Postgres

89 89 Otázky

90 Relačná algebra (RA) a implementácia operácií RA Podľa [2]

91 91 Relačná algebra Relácia - podmnožina karteziánskeho súčinu R  D 1 ...  D n Relačná algebra: –Formálny jazyk pre relačný model –Základný súbor operácií pre vyhľadávacie dotazy

92 92 Selekcia  Projekcia  Kartéziánsky súčin  Spojenie (join) (theta-, equi-, natural- ) Množinové (union kompatibilné): –Prienik (intersection)  –Zjednotenie (union)  –Rozdiel (difference) \ Operácie relačnej algebry

93 93 Elementary conditionEC and condition C Definition: Elementary (simple) condition EC is clause of the form: where operator is from the set of relational operators {=,, =,≠}. Definition: Condition C is clause of the form : [NOT] EC1 [{OR | AND } [ [NOT] EC2] …]

94 94 Examples (O1):  SSN='123456789' (EMPLOYEE) (O2):  DNUMBER>5 (DEPARTMENT) (O3):  DNO=5 (EMPLOYEE) (O4):  DNO=5 AND SALARY>30000 AND SEX=' F' (EMPLOYEE) (O5):  ESSN='123456789' AND PNO=10 (WORKS_ON)

95 95 SELECT operation Definition:  c = {  t i  R | c(t i )}(3-value logic) Implementation: –Linear search –Binary search –Using a primary index (or hash key) –Using a primary index to retrieve multiple records –Using a clustering index to retrieve multiple records –Using a secondary (B+-tree) index on an equality comparison –...

96 96 S1:Linear search (brute force) Retrieve every record in the file, and test whether its attribute values satisfy the selection condition. for every t i if (c(t i ) == TRUE) output(t i )

97 97 S2:Binary search If the selection condition involves an equality comparison on a key attribute on which the file is ordered.  SSN='123456789' (EMPLOYEE)

98 98 S3: Using a primary index (or hash key) If the selection condition involves an equality comparison on a key attribute with a primary index (or hash key), use the primary index (or hash key) to retrieve the record. Note that this condition retrieves a single record (at most).  SSN='123456789' (EMPLOYEE)

99 99 S4: Using a primary index to retrieve multiple records If the comparison condition is >, >=, <', or <= on a key field with a primary index, use the index to find the record satisfying the corresponding condition  DNUMBER>5 (DEPARTMENT) (selectivity, distribution)  DNO=5 AND SALARY>30000 AND SEX=' F' (EMPLOYEE)

100 100 S5: Using a clustering index to retrieve multiple records If the selection condition involves an equality comparison on a non key attribute with a clustering index (for example, DNO = 5 in S3) use the index to retrieve all the records satisfying the condition.  DNO=5 (EMPLOYEE) (if clusterred on DNO)

101 101 S6: Using a secondary (B+-tree) index on an equality comparison This search method can be used to retrieve a single record if the indexing field is a key (has unique values) or to retrieve multiple records if the indexing field is not a key. This can also be used for comparisons involving >, >=, <, or <=.

102 102 S7: Conjunctive selection using an individual index If an attribute involved in any single simple condition in the conjunctive condition has an access path that permits the use of one of the Methods S2 (binary search) to S6 (B- tree), use that condition to retrieve the records and then check whether each retrieved record satisfies the remaining simple conditions in the conjunctive condition.

103 103 S8:Conjunctive selection using a composite index If two or more attributes are involved in equality conditions in the conjunctive condition and a composite index (or hash structure) exists on the combined fields-for example, if an index has been created on the composite key (ESSN, PNO) of the WORKS_ON file for O5-we can use the index directly.

104 104 JOIN operation R ⋈ c S = {t i  R,t j  S| c(t i,t j ) == TRUE } Implementácia –Nested-loop join (brute force) –Single-loop join (using an access structure to retrieve the matching records) –Sort-merge join –Hash-join

105 105 J1. Nested-loop join (brute force) For each record t in R (outer loop), retrieve every record s from S (inner loop) and test whether the two records satisfy the join condition c (incl. theta-join). for each t i for each s j if( c(t i,s j ) == TRUE ) output(t i.s j ) Improvement - nested-block join

106 106 J2. Single-loop join (using an access structure to retrieve the matching records) If an index (or hash key) exists for one of the two join attributes-say, B of S, retrieve each record t in R, one at a time (single loop), and then use the access structure to retrieve directly all matching records s from S that satisfy t[B] =t[A] (equi-join).

107 107 J3. Sort-merge join If the records of R and S are physically sorted (ordered) by value of the join attributes A and B, respectively, we can implement the join in the most efficient way possible. Both files are scanned concurrently in order of the join attributes, matching the records that have the same values for A and B. If the files are not sorted, they may be sorted first by using external sorting.

108 108 J4. Hash-join The records of files R and S are both hashed to the same hash file, using the same hashing function on the join attributes A of R and B of S as hash keys. First, a single pass through the file with fewer records (say, R) hashes its records to the hash file buckets (partitioning phase - records of R are partitioned into the hash buckets). In the second phase (probing phase), a single pass through the other file (S) then hashes each of its records to probe the appropriate bucket, and that record is combined with all matching records from R in that bucket.

109 109 PROJECT operation  (R) Implementation: –straightforward to implement if includes a key of relation R – the same number of records. –If does not include a key of R, duplicate tuples must be eliminated (sorting, hashing). –Index can be used in some cases.

110 110 SET operation CARTESIAN PRODUCT operation R  S is quite expensive, because its result includes a record for each combination of records from R and S. Can be improved by processing at the block level UNION, INTERSECTION, and SET DIFFERENCE apply only to union-compatible relations (that have the same number of attributes and the same attribute domains). Implementation - sort-merge technique or hashing

111 111 Sort-merge technique (for the SET operation) The two relations are sorted on the same attributes. After sorting, a single scan through each relation is sufficient to produce the result. For example, we can implement the UNION operation, R  S, by scanning and merging both sorted files concurrently, and whenever the same tuple exists in both relations, only one is kept in the merged result. For the INTERSECTION operation, R  S, we keep in the merged result only those tuples that appear in both relations.

112 112 Hashing (for the SET operation) One table is partitioned and the other is used to probe the appropriate partition. For example, to implement R  S, first hash (partition) the records of R; then, hash (probe) the records of S, but do not insert duplicate records in the buckets. To implement R  S, first partition the records of R to the hash file. Then, while hashing each record of S, probe to check if an identical record from R is found in the bucket, and if so add the record to the result file. To implement R - S, first hash the records of R to the hash file buckets. While hashing (probing) each record of S, if an identical record is found in the bucket, remove that record from the bucket.

113 113 Implementing Aggregate Operations The aggregate operators (MIN, MAX, COUNT, AVERAGE, SUM), when applied to an entire table, can be computed by a table scan or by using an appropriate index, if available. For example, consider the following SQL query: SELECT MAX(SALARY) FROM EMPLOYEE; If an (ascending) index on SALARY exists for the EMPLOYEE relation, then the optimizer can decide on using the index to search for the largest value by following the rightmost pointer in each index node from the root to the rightmost leaf.

114 114 Implementing Aggregate Operations The dense index can be used for the COUNT, AVERAGE, and SUM aggregates. The associated computation would be applied to the values in the index.

115 115 GROUP BY clause When a GROUP BY clause is used in a query, the aggregate operator must be applied separately to each group of tuples. In this case, the computation is more complex - the table must first be partitioned into subsets of tuples, where each partition (group) has the same value for the grouping attributes. Sorting or hashing are used to partition the file into the appropriate groups If a clustering index exists on the grouping attributes, then the records are already partitioned (grouped) into the appropriate subsets.

116 116 Otázky

117 Query processing and optimization Based on [2]

118 118 Query processing

119 119 Execution (query) plan Logical query plan Physical query plan

120 120 Logical query plan SQL – deklaratívny jazyk Potrebujeme transformovať dotaz v SQL (SELECT) na (previazanú) postupnosť operácií relačnej algebry Optimalizovať na logickej úrovni

121 121 Query tree A query tree - tree data structure that corresponds to a relational algebra expression. It represents the input relations of the query as leaf nodes of the tree, and represents the relational algebra operations as internal nodes. An execution of the query tree consists of executing an internal node operation whenever its operands are available and then replacing that internal node by the relation that results from executing the operation. The execution terminates when the root node is executed and produces the result relation for the query.

122 122 Query tree – example

123 123 Query tree – example (cont.) Example: For every project located in ‘ Stafford ’, retrieve the project number, the controlling department number and the department manager ’ s last name, address and birthdate. Relation algebra:  PNUMBER, DNUM, LNAME, ADDRESS, BDATE (((  PLOCATION=‘STAFFORD’ (PROJECT)) ⋈ DNUM=DNUMBER (DEPARTMENT)) ⋈ MGRSSN=SSN (EMPLOYEE)) SQL query: Q2: SELECT P.NUMBER,P.DNUM,E.LNAME, E.ADDRESS, E.BDATE FROM PROJECT AS P,DEPARTMENT AS D, EMPLOYEE AS E WHERE P.DNUM=D.DNUMBER AND D.MGRSSN=E.SSN AND P.PLOCATION= ‘ STAFFORD ’ ;

124 124 Query tree – example

125 125 Inicial (canonical) query tree

126 126 Konštrukcia „canonical query tree“ Nad všetkými reláciami vybuduj „veľký“ kartézsky súčin Vyselektuj záznamy podľa úplnej podmienky vo WHERE klauzule Sprav projekciu výsledku podľa atribútov za SELECT klauzulou

127 127 Konštrukcia „canonical query tree“ SELECT FROM T 1, …, T n WHERE C V relačnej algebre:  (  c (  (T 1, …, T n ) ) ) T1, …, Tn X cc 

128 128 Heuristic Optimization of Query Trees The same query could correspond to many different relational algebra expressions — and hence many different query trees. The task of heuristic optimization of query trees is to find a final query tree that is efficient to execute. Example: Q: SELECT LNAME FROM EMPLOYEE, WORKS_ON, PROJECT WHERE PNAME = ‘ AQUARIUS ’ AND PNMUBER=PNO AND ESSN=SSN AND BDATE > ‘ 1957-12-31 ’ ;

129 129 Canonical query tree

130 130 Steps in converting QT (1)

131 131 Steps in converting QT (2)

132 132 Transformation Rules for query optimization  Cascade of  : A conjunctive selection condition can be broken up into a cascade (sequence) of individual s operations:  c1 AND c2 AND... AND cn (R)   c1 (  c2 (...(  cn (R))...) )  Commutativity of  : The  operation is commutative:  c1 (  c2 (R))   c2 (  c1 (R))  Cascade of  : In a cascade (sequence) of  operations, all but the last one can be ignored:  List1 (  List2 (...(  Listn (R))...) ) =  List1 (R)

133 133 Transformation Rules for query optimization  Commuting  with  : If the selection condition c involves only the attributes A1,..., An in the projection list, the two operations can be commuted:  A1, A2,..., An (  c (R)) =  c (  A1, A2,..., An (R))  Comutativity of ⋈ ( and x ): The ⋈ operation is commutative as is the x operation: R ⋈ C S = S ⋈ C R; R x S = S x R

134 134 Transformation Rules for query optimization  Commuting  with ⋈ (or x  ): If all the attributes in the selection condition c involve only the attributes of one of the relations being joined - say, R - the two operations can be commuted as follows :  c ( R ⋈ S )  (  c (R)) ⋈ S Alternatively, if the selection condition c can be written as (c1 and c2), where condition c1 involves only the attributes of R and condition c2 involves only the attributes of S, the operations commute as follows:  c ( R ⋈ S )  (  c1 (R)) ⋈ (  c2 (S))

135 135 Transformation Rules for query optimization  Commuting  with ⋈ (or x ): Suppose that the projection list is L = {A1,..., An, B1,..., Bm}, where A1,..., An are attributes of R and B1,..., Bm are attributes of S. If the join condition c involves only attributes in L, the two operations can be commuted as follows:  L ( R ⋈ C S )  (  A1,..., An (R)) ⋈ C (  B1,..., Bm (S)) If the join condition c contains additional attributes not in L, these must be added to the projection list, and a final  operation is needed.

136 136 Transformation Rules for query optimization  Commutativity of set operations: The set operations  and  are commutative but – is not.  Associativity of ⋈, x, , and  : These four operations are individually associative; that is, if  stands for any one of these four operations (throughout the expression), we have ( R  S )  T  R  ( S  T )  Commuting  with set operations: The  operation commutes with  , , and –. If  stands for any one of these three operations, we have  c ( R  S )  (  c (R))  (  c (S))

137 137 Transformation Rules for query optimization  The  operation commutes with υ.  L ( R  S )  (  L (R))  (  L (S))  Converting a (  x  sequence into ⋈ : If the condition c of a  that  follows a  corresponds to a join condition, convert the (  x  sequence into a ⋈ as follows: (  C (R x S)) = (R ⋈ C S)  Other transformations

138 138 Outline of a Heuristic Algebraic Optimization Algorithm  Using rule 1, break up any select operations with conjunctive conditions into a cascade of select operations.  Using rules 2, 4, 6, and 10 concerning the commutativity of select with other operations, move each select operation as far down the query tree as is permitted by the attributes involved in the select condition.  Using rule 9 concerning associativity of binary operations, rearrange the leaf nodes of the tree so that the leaf node relations with the most restrictive select operations are executed first in the query tree representation.

139 139 Outline of a Heuristic Algebraic Optimization Algorithm  Using Rule 12, combine a cartesian product operation with a subsequent select operation in the tree into a join operation.  Using rules 3, 4, 7, and 11 concerning the cascading of project and the commuting of project with other operations, break down and move lists of projection attributes down the tree as far as possible by creating new project operations as needed.  Identify subtrees that represent groups of operations that can be executed by a single algorithm.

140 140 Summary of Heuristics for Algebraic Optimization  The main heuristic is to apply first the operations that reduce the size of intermediate results.  Perform select operations as early as possible to reduce the number of tuples and perform project operations as early as possible to reduce the number of attributes. (This is done by moving select and project operations as far down the tree as possible.)  The select and join operations that are most restrictive should be executed before other similar operations. (This is done by reordering the leaf nodes of the tree among themselves and adjusting the rest of the tree appropriately.)

141 141 Physical Query ( Execution ) Plans An physical query plan for a relational algebra query consists of a combination of the relational algebra query tree and information about the access methods to be used for each relation as well as the methods to be used in computing the relational operators stored in the tree.

142 142 Úloha Ako “obsadiť“ jednotlivé operácie RA konkrétnymi implementáciami? Potreba ohodnotenia jednotlivých implementácií – cost based optimization Mali by sa vybudovať a prepočítať všetky možnosti Ak ich je veľa, preverujú sa len niektoré vetvy

143 143 Cost Components for Query Execution 1.Access cost to secondary storage 2.Storage cost 3.Computation cost 4.Memory usage cost 5.Communication cost Note: Different database systems may focus on different cost components.

144 144 Catalog Information Used in Cost Functions –Information about the size of a file number of records (tuples) (r), record size (R), number of blocks (b) blocking factor (bfr) –Information about indexes and indexing attributes of a file Number of levels (x) of each multilevel index Number of first-level index blocks (b I1 ) Number of distinct values (d) of an attribute Selectivity (sl) of an attribute Selection cardinality (s) of an attribute. (s = sl * r)

145 145 Otázky

146 Ladenie dotazov

147 147 Príklad INFORMIX (1) Detailnejsi opis - Sample Query Plan Reports.pdf

148 148 Príklad INFORMIX (2)

149 149 Príklad INFORMIX (3)

150 150 MS-SQL

151 Späť k DWH

152 152 Efektívna implementácia Bitmapové indexy Bitmapové join indexy C-store

153 153 Otázky


Download ppt "Ján GENČI PDT 2009 Systém riadenia bázy dát (Database Management System)"

Similar presentations


Ads by Google