Presentation on theme: "Indexes and B-Trees Lecture 9 R & G Chapters 8 & 9"— Presentation transcript:
1Indexes and B-TreesLecture 9R & G Chapters 8 & 9“If I had eight hours to chop down a tree, I'd spend six sharpening my ax.”Abraham LincolnThe slides for this text are organized into several modules. Each lecture contains about enough material for a 1.25 hour class period. (The time estimate is very approximate--it will vary with the instructor, and lectures also differ in length; so use this as a rough guideline.) This covers Lectures 3 and 4 (of 6) in Module (2).Module (1): Introduction (DBMS, Relational Model)Module (2): Storage and File Organizations (Disks, Buffering, Indexes)Module (3): Database Concepts (Relational Queries, DDL/ICs, Views and Security)Module (4): Relational Implementation (Query Evaluation, Optimization)Module (5): Database Design (ER Model, Normalization, Physical Design, Tuning)Module (6): Transaction Processing (Concurrency Control, Recovery)Module (7): Advanced Topics1
2Administrivia Homework 1 Due Tonight, 10pm Homework 2 Available Today, Due 3 weeks from todayMidterm Exam 1 will be a week from ThursdayIt will be in class, at the usual timeNext Tuesday’s class will be a reviewMore SQL Exercises on the Class Website
3Review Last two weeks: Formal Query Languages: Rel. Algebra & Calculus Actual Query Language: SQLThis week: IndexesTree Indexes (HW2)Hash IndexesNext week:ReviewMidterm 1
5Review: Use NOT Exists for Division Recall: X/Y means only give me X tuples that have a match in Y.Find sailors who’ve reserved all boats.X = set of sailors and Y = set of all boats with reservations.SELECT S.snameFROM Sailors SWHERE NOT EXISTS(SELECT B.bidFROM Boats BWHERE NOT EXISTS(SELECT R.bidFROM Reserves RWHERE R.bid=B.bidAND R.sid=S.sid))Find Sailors S such that ...there is no boat B...without a reservation by Sailor S
6Division SELECT S.sname FROM Sailors S WHERE NOT EXISTS (SELECT B.bid FROM Boats BWHERE NOT EXISTS(SELECT R.bidFROM Reserves RWHERE R.bid=B.bidAND R.sid=S.sid))101103132ReservesSailorssidbidday11039/1229/1339/14101BoatsRsidsnameratingage1Frodo7222Bilbo393Sam827bidbnamecolor101Ninared103PintablueSBRSRBRSR
7Null Values Values are sometimes unknown (e.g., a rating has not been assigned) orinapplicable (e.g., no spouse’s name).SQL provides a special value null for such situations.The presence of null complicates many issues. E.g.:Special operators needed to check if value is/is not null.“rating>8” - true or false when rating is null? What about AND, OR and NOT connectives?Need a 3-valued logic (true, false and unknown).Meaning of constructs must be defined carefully. (e.g., WHERE clause eliminates rows that don’t evaluate to true.)New operators (in particular, outer joins) possible/needed.
9Null Values in SQL “Where” clause must evaluate to true “IS NULL” operator, e.g. “where name is null”“IS NOT NULL” operatorOuter Joins: Left, Right, Full
10SELECT s.sid, s.name, r.bid FROM Sailors s LEFT OUTER JOIN Reserves r ON s.sid = r.sid
11SELECT r.sid, b.bid, b.name FROM Reserves r RIGHT OUTER JOIN Boats b ON r.bid = b.bid
12Review – Buffer Management and Files Storage of DataFields, either fixed or variable length...Stored in Records...Stored in Pages...Stored in FilesIf data won’t fit in RAM, store on DiskNeed Buffer Pool to hold pages in RAMDifferent strategies decide what to keep in pool
13Today: File Organization How to keep pages of records on diskbut must support operations:scan all recordssearch for a record id “RID”search for record(s) with certain valuesinsert new recordsdelete old records
14Alternative File Organizations Many alternatives exist, tradeoffs for each:Heap files:Suitable when typical access is file scan of all records.Sorted Files:Best for retrieval in search key orderAlso good for search based on search keyIndexes: Organize records via trees or hashing.Like sorted files, speed up searches for search key fieldsUpdates are much faster than in sorted files.
15IndexesOften want to get records byvalues in one or more fields, e.g.,Find all students in the “CS” departmentFind all students with a gpa > 3An index on a file is a:Disk-based data structureSpeeds up selections on the search key fields for the index.Any subset of the fields of a relation can be index search keySearch key is not the same as key(e.g. doesn’t have to be unique ID).An indexContains a collection of key/data entry pairsSupports efficient retrieval of all records with a given search key value k.
16Index Classification What selections does it support? What does index actually store?3 alternatives:Data record with key value k<k, rid of data record><k, list of rids of data records>Clustered vs. Unclustered IndexesSingle Key vs. Composite IndexesTree-based, hash-based, otherCan have multiple (different) indexes per file.E.g. file sorted by age, with a hash index on salary and a B+tree index on name.
17First Question to Ask About an Index What kinds of selections does it support?Selections of form field <op> constantEquality selections (op is =)Range selections (op is one of <, >, <=, >=, BETWEEN)More exotic selections:2-dimensional ranges (“east of Berkeley and west of Truckee and North of Fresno and South of Eureka”)Or n-dimensional2-dimensional distances (“within 2 miles of Soda Hall”)Ranking queries (“10 restaurants closest to VLSB”)Regular expression matches, genome string matches, etc.One common n-dimensional index: R-tree
18What data is held by the index? Alternative 1: Actual data record (with key value k)Index structure is file organization for data records (like Heap files or sorted files).At most one index on a table can use Alternative 1.Saves pointer lookupsCan be expensive to maintain with insertions and deletions.
19What data is held by the index? (Contd.) Alternative 2<k, rid>and Alternative 3<k, list of rids>Easier to maintain than Alt 1.At most one index can use Alternative 1; any others must use Alternatives 2 or 3.Alternative 3 more compact than Alternative 2, but leads to variable sized data entries even if search keys are of fixed length.Even worse, for large rid lists the data entry might have to span multiple pages!
20Clustered and Unclustered Clustered vs. unclustered:If order of data records is the same as, or `close to’, order of index data entries, then called clustered index.A file can be clustered on at most one search key.Cost to retrieve data records with index varies greatly based on whether index clustered or not!Alternative 1 implies clustered, but not vice-versa.
21Clustered vs. Unclustered Index Suppose that Alternative (2) is used for data entries, and that the data records are stored in a Heap file.To build clustered index, first sort the Heap file (with some free space on each block for future inserts).Overflow blocks may be needed for inserts. (Thus, order of data recs is `close to’, but not identical to, the sort order.)Index entriesUNCLUSTEREDCLUSTEREDdirect search fordata entriesData entriesData entries(Index File)(Data file)Data RecordsData Records
22Unclustered vs. Clustered Indexes What are the tradeoffs????Clustered ProsEfficient for range searchesMay be able to do some types of compressionPossible locality benefits (related data?)Clustered ConsExpensive to maintain (on the fly or sloppy with reorganization)
23Hash-Based Indexes Good for equality selections. Index is a collection of buckets. Bucket = primary page plus zero or more overflow pages.Hashing function h:h(r) = bucket in which record r belongs.h looks at the search key fields of r.If Alternative (1) is used, the buckets contain the data records; otherwise, they contain <key, rid> or <key, rid-list> pairs.2
24B+ Tree IndexesNon-leafPagesLeafPagesLeaf pages contain data entries, and are chained (prev & next)Non-leaf pages contain index entries and direct searches:index entryPKPK12PKP12mm4
25Comparing File Organizations Heap files (random order; insert at eof)Sorted files, sorted on <age, sal>Clustered B+ tree file, Alternative (1), search key <age, sal>Heap file with unclustered B + tree index on search key <age, sal>Heap file with unclustered hash index on search key <age, sal>
26Operations to Compare Scan: Fetch all records from disk Fetch all records in sorted orderEquality searchRange selectionInsert a recordDelete a record
27Cost Model for Analysis I/O cost 150,000 times more than hash functionWe ignore CPU costs, for simplicityB: The number of data pagesR: Number of records per pageF: Fanout of B-treeAverage-case analysis; based on several simplistic assumptions.Good enough to show the overall trends!
28Assumptions in Our Analysis Heap Files:Equality selection on key; exactly one match.Sorted Files:Files compacted after deletions.Indexes:Alt (2), (3): data entry size = 10% size of recordHash: No overflow buckets.80% page occupancy => File size = 1.25 data sizeTree: 67% occupancy (this is typical).Implies file size = 1.5 data size4
29I/O Cost of Operations Heap File Scan all records B Get all in sort order4BEquality Search0.5 BRange SearchInsert2Delete0.5B + 1I/O Cost of OperationsB: Number of data pages (packed)R: Number of records per pageS: Time required for equality search
30I/O Cost of Operations Sorted File Scan all records B Get all in sort orderEquality Searchlog2 BRange SearchS + # matching pagesInsertS + BDeleteI/O Cost of OperationsB: Number of data pages (packed)R: Number of records per pageS: Time required for equality search
31I/O Cost of Operations Clustered Tree Scan all records 1.5 B Get all in sort orderEquality SearchlogF (1.5 B)Range SearchS + #matching pagesInsertS + 1Delete0.5B + 1I/O Cost of OperationsB: Number of data pages (packed)R: Number of records per pageF: Fanout of B-TreeS: Time required for equality search
32I/O Cost of Operations Unclustered Tree Scan all records B (ignore index)Get all in sort order4BEquality SearchlogF (.15 B) + 1Range SearchS + #matching recordsInsertS + 2DeleteI/O Cost of OperationsB: Number of data pages (packed)R: Number of records per pageF: Fanout of B-TreeS: Time required for equality search
33I/O Cost of Operations Hash Index Scan all records B (ignore index) Get all in sort order4BEquality Search2Range SearchInsert4DeleteS + 2I/O Cost of OperationsB: Number of data pages (packed)R: Number of records per pageS: Time required for equality search
34I/O Cost of Operations B: The number of data pages R: Number of records per pageF: Fanout of B-TreeS: Time required for equality search* Don’t Use IndexI/O Cost of OperationsHeap FileSorted FileClustered TreeUnclustered TreeHash IndexScan all recordsB1.5 BB*Get all in sort order4B4B*Equality Search0.5 Blog2 BlogF (1.5 B)logF (.15 B) + 12Range SearchS + #matching pagesS + #matching recordsInsertS + BS + 1S + 24Delete0.5B + 1
35Index Selection Guidelines Attributes in WHERE clause are candidates for index keys.Exact match condition suggests hash index.Range query suggests tree index.Clustering is especially useful for range queries; can also help on equality queries if there are many duplicates.Multi-attribute search keys should be considered when a WHERE clause contains several conditions.Order of attributes is important for range queries.Such indexes sometimes enable index-only strategiesFor index-only strategies, clustering is not important!Choose indexes that benefit as many queries as possible.Since only one index can be clustered per table, choose it based on important queries that would benefit the most from clustering.14
36B+ Tree: The Most Widely Used Index Supports equality and range-searches efficiently.Insert/delete at log F N cost; keep tree height-balanced. (F = fanout, N = # leaf pages)Minimum 50% occupancy (except for root). Each node contains d <= m <= 2d entries. The parameter d is called the order of the tree.Index Entries(Direct search)Data Entries("Sequence set")9
37Example B+ TreeSearch begins at root, and key comparisons direct it to a leaf (as in ISAM).Search for 5*, 15*, all data entries >= 24* ...Root1724302*3*5*7*14*16*19*20*22*24*27*29*33*34*38*39*13Based on the search for 15*, we know it is not in the tree!10
38B+ Trees in Practice Typical order: 100. Typical fill-factor: 67%. average fanout = 133Typical capacities:Height 4: 1334 = 312,900,700 recordsHeight 3: 1333 = 2,352,637 recordsCan often hold top levels in buffer pool:Level 1 = page = KbytesLevel 2 = pages = MbyteLevel 3 = 17,689 pages = 133 MBytes
39Inserting a Data Entry into a B+ Tree Find correct leaf L.Put data entry onto L.If L has enough space, done!Else, must split L (into L and a new node L2)Redistribute entries evenly, copy up middle key.Insert index entry pointing to L2 into parent of L.This can happen recursivelyTo split index node, redistribute entries evenly, but push up middle key. (Contrast with leaf splits.)Splits “grow” tree; root split increases height.Tree growth: gets wider or one level taller at top.6
40Example B+ Tree - Inserting 8* Root131724302*3*5*7*14*16*19*20*22*24*27*29*33*34*38*39*13
41Example B+ Tree - Inserting 8* Root1751324302*3*5*7*8*14*16*19*20*22*24*27*29*33*34*38*39*Notice that root was split, leading to increase in height.In this example, we can avoid split by re-distributing entries; however, this is usually not done in practice.13
42Inserting 8* into Example B+ Tree Entry to be inserted in parent node.Observe how minimum occupancy is guaranteed in both leaf and index pg splits.Note difference between copy-up and push-up; be sure you understand the reasons for this.5(Note that 5 is…s copied up andcontinues to appear in the leaf.)2*3*5*7*8*Entry to be inserted in parent node.(Note that 17 is pushed up and only17appears once in the index. Contrast…this with a leaf split.)513243012
43Deleting a Data Entry from a B+ Tree Start at root, find leaf L where entry belongs.Remove the entry.If L is at least half-full, done!If L has only d-1 entries,Try to re-distribute, borrowing from sibling (adjacent node with same parent as L).If re-distribution fails, merge L and sibling.If merge occurred, must delete entry (pointing to L or sibling) from parent of L.Merge could propagate to root, decreasing height.14
45Example Tree (including 8*) Delete 19* and 20* ... Root1751324302*3*5*7*8*14*16*19*20*22*24*27*29*33*34*38*39*Deleting 19* is easy.15
46Example Tree (including 8*) Delete 19* and 20* ... Root1751327302*3*5*7*8*14*16*22*24*27*29*33*34*38*39*Deleting 19* is easy.Deleting 20* is done with re-distribution. Notice how middle key is copied up.15
47... And Then Deleting 24* Must merge. Observe `toss’ of index entry (on right), and `pull down’ of index entry (below).3022*27*29*33*34*38*39*Root51317302*3*5*7*8*14*16*22*27*29*33*34*38*39*16
48Summary Alternative file organizations, tradeoffs for each If selection queries are frequent, sorting the file or building an index is important.Hash-based indexes only good for equality search.Sorted files and tree-based indexes best for range search; also good for equality search. (Files rarely kept sorted in practice; B+ tree index is better.)Index is a collection of data entries plus a way to quickly find entries with given key values.14
49Summary (Contd.)Data entries can be actual data records, <key, rid> pairs, or <key, rid-list> pairs.Choice orthogonal to indexing technique used to locate data entries with a given key value.Can have several indexes on a given file of data records, each with a different search key.Indexes can beclustered, unclusteredB-tree, hash table, etc.15
50Summary (Contd.)Understanding the nature of the workload for the application, and the performance goals, is essential to developing a good design.What are the important queries and updates? What attributes/relations are involved?Indexes must be chosen to speed up important queries (and perhaps some updates!).Index maintenance overhead on updates to key fields.Choose indexes that can help many queries, if possible.Build indexes to support index-only strategies.Clustering is an important decision; only one index on a given relation can be clustered!Order of fields in composite index key can be important.