QUIZ: Buffer replacement policies

Similar documents
Database System Concepts, 6 th Ed. Silberschatz, Korth and Sudarshan See for conditions on re-use

Chapter 11: Indexing and Hashing" Chapter 11: Indexing and Hashing"

Chapter 11: Indexing and Hashing

Chapter 11: Indexing and Hashing

Chapter 11: Indexing and Hashing

Chapter 12: Indexing and Hashing. Basic Concepts

Database index structures

Chapter 12: Indexing and Hashing

Chapter 12: Indexing and Hashing

Chapter 11: Indexing and Hashing

Database System Concepts, 5th Ed. Silberschatz, Korth and Sudarshan See for conditions on re-use

Intro to DB CHAPTER 12 INDEXING & HASHING

Hashing file organization

Chapter 12: Indexing and Hashing (Cnt(

CS34800 Information Systems

CSIT5300: Advanced Database Systems

Indexing: Overview & Hashing. CS 377: Database Systems

Indexing: B + -Tree. CS 377: Database Systems

key h(key) Hash Indexing Friday, April 09, 2004 Disadvantages of Sequential File Organization Must use an index and/or binary search to locate data

File Structures and Indexing

Physical Level of Databases: B+-Trees

CSE 530A. B+ Trees. Washington University Fall 2013

Chapter 12: Query Processing. Chapter 12: Query Processing

Indexing. Week 14, Spring Edited by M. Naci Akkøk, , Contains slides from 8-9. April 2002 by Hector Garcia-Molina, Vera Goebel

Physical Database Design: Outline

QUIZ: Is either set of attributes a superkey? A candidate key? Source:

Material You Need to Know

Chapter 12: Query Processing

Announcements. Reading Material. Recap. Today 9/17/17. Storage (contd. from Lecture 6)

Find the block in which the tuple should be! If there is free space, insert it! Otherwise, must create overflow pages!

Kathleen Durant PhD Northeastern University CS Indexes

Advanced Database Systems

Instructor: Amol Deshpande

Query Processing. Debapriyo Majumdar Indian Sta4s4cal Ins4tute Kolkata DBMS PGDBA 2016

CMSC 424 Database design Lecture 13 Storage: Files. Mihai Pop

Some Practice Problems on Hardware, File Organization and Indexing

Topics to Learn. Important concepts. Tree-based index. Hash-based index

Extra: B+ Trees. Motivations. Differences between BST and B+ 10/27/2017. CS1: Java Programming Colorado State University

Introduction to Indexing 2. Acknowledgements: Eamonn Keogh and Chotirat Ann Ratanamahatana

CS143: Index. Book Chapters: (4 th ) , (5 th ) , , 12.10

Physical Database Design

Storage hierarchy. Textbook: chapters 11, 12, and 13

Physical Disk Structure. Physical Data Organization and Indexing. Pages and Blocks. Access Path. I/O Time to Access a Page. Disks.

Lecture 8 Index (B+-Tree and Hash)

Chapter 13: Query Processing

DATABASE PERFORMANCE AND INDEXES. CS121: Relational Databases Fall 2017 Lecture 11

Indexing. Jan Chomicki University at Buffalo. Jan Chomicki () Indexing 1 / 25

! A relational algebra expression may have many equivalent. ! Cost is generally measured as total elapsed time for

Chapter 13: Query Processing Basic Steps in Query Processing

(i) It is efficient technique for small and medium sized data file. (ii) Searching is comparatively fast and efficient.

Access Methods. Basic Concepts. Index Evaluation Metrics. search key pointer. record. value. Value

Database System Concepts

Chapter 17 Indexing Structures for Files and Physical Database Design

CPS352 Lecture - Indexing

CMSC424: Database Design. Instructor: Amol Deshpande

Query Processing & Optimization

Systems Infrastructure for Data Science. Web Science Group Uni Freiburg WS 2014/15

CSE 544 Principles of Database Management Systems. Magdalena Balazinska Winter 2009 Lecture 6 - Storage and Indexing

CSC 261/461 Database Systems Lecture 17. Fall 2017

Something to think about. Problems. Purpose. Vocabulary. Query Evaluation Techniques for large DB. Part 1. Fact:

CS-245 Database System Principles

Indexing and Hashing

RAID in Practice, Overview of Indexing

CARNEGIE MELLON UNIVERSITY DEPT. OF COMPUTER SCIENCE DATABASE APPLICATIONS

Indexing Methods. Lecture 9. Storage Requirements of Databases

Indexing. Chapter 8, 10, 11. Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1

Tree-Structured Indexes

Indexing. Announcements. Basics. CPS 116 Introduction to Database Systems

Selection Queries. to answer a selection query (ssn=10) needs to traverse a full path.

The physical database. Contents - physical database design DATABASE DESIGN I - 1DL300. Introduction to Physical Database Design

CSE 562 Database Systems

Data Management for Data Science

Remember. 376a. Database Design. Also. B + tree reminders. Algorithms for B + trees. Remember


COMP 430 Intro. to Database Systems. Indexing

CSE 544 Principles of Database Management Systems

Datenbanksysteme II: Caching and File Structures. Ulf Leser

System Structure Revisited

CS 525: Advanced Database Organization 04: Indexing

Classifying Physical Storage Media. Chapter 11: Storage and File Structure. Storage Hierarchy (Cont.) Storage Hierarchy. Magnetic Hard Disk Mechanism

Classifying Physical Storage Media. Chapter 11: Storage and File Structure. Storage Hierarchy. Storage Hierarchy (Cont.) Speed

Lecture 13. Lecture 13: B+ Tree

Database Management and Tuning

Introduction to Data Management. Lecture 15 (More About Indexing)

Outline. Database Management and Tuning. What is an Index? Key of an Index. Index Tuning. Johann Gamper. Unit 4

Chapter 12: Query Processing

CS127: B-Trees. B-Trees

Tree-Structured Indexes

Fundamentals of Database Systems Prof. Arnab Bhattacharya Department of Computer Science and Engineering Indian Institute of Technology, Kanpur

Database Applications (15-415)

Spring 2013 CS 122C & CS 222 Midterm Exam (and Comprehensive Exam, Part I) (Max. Points: 100)

amiri advanced databases '05

Chapter 12: Query Processing

Chapter 17. Disk Storage, Basic File Structures, and Hashing. Records. Blocking

Announcement. Reading Material. Overview of Query Evaluation. Overview of Query Evaluation. Overview of Query Evaluation 9/26/17

Database Technology. Topic 7: Data Structures for Databases. Olaf Hartig.

Overview of Storage and Indexing

Database Applications (15-415)

Tree-Structured Indexes. Chapter 10

CSE 444: Database Internals. Lectures 5-6 Indexing

Transcription:

QUIZ: Buffer replacement policies Compute join of 2 relations r and s by nested loop: for each tuple tr of r do for each tuple ts of s do if the tuples tr and ts match do something that doesn t require disk access Assume that: tr has 3 tuples ts has 5 tuples All tuples have the same size There is only one buffer, and it can hold 5 tuples total How many disk accesses are needed for the following replacement algorithms: LRU MRU 11.1

QUIZ: Buffer replacement policies Compute join of 2 relations r and s by nested loop: for each tuple tr of r do for each tuple ts of s do if the tuples tr and ts match do something Assume that: r has 3 tuples s has 5 tuples All tuples have the same size There is a separate buffer for each table: r buffer can hold 2 tuples, s buffer can hold 3 tuples. How many disk accesses are needed for the following replacement algorithms: LRU(tr)/LRU(ts) LRU(tr)/MRU(ts) These questions are to be solved in the lab; they re included here for reference. 11.2

Chapter 11: Indexing and Hashing Database System Concepts, 6 th Ed. See www.db-book.com for conditions on re-use

Basic Concepts Indexing mechanisms are used to speed up access to data. Search Key - attribute to set of attributes used to look up records in a file. An index file consists of records (called index entries) of the form search-key pointer Indices are typically much smaller than the original, e.g.: Table of contents in a book Index in a book Catalog in a library Inventory in a warehouse 11.4

Basic Concepts search-key pointer Two basic kinds of indices: Ordered indices: search keys are stored in sorted order Hash indices: search keys are distributed uniformly across buckets using a hash function. 11.5

Index Evaluation Metrics What are the access types supported efficiently, e.g.: records with a specified value in the attribute? records with an attribute value falling in a specified range of values? all records in the file? Access time Insertion time Deletion time Space overhead 11.6

11.2 Ordered Indices To use an ordered index, we need an index-sequential file = file that is stored sequentially, according to some attribute: This attribute (PK?) will be used as primary index 11.7

11.2 Ordered Indices In an ordered index, index entries are stored sorted on the search key value E.g. author catalog in library. Primary index: in a sequentially ordered file, it is the index whose search key specifies the sequential order of the file. Also called clustering index The search key of a primary index is usually (but not necessarily) the PK. Secondary index: an index whose search key specifies an order different from the sequential order of the file. Also called non-clustering index. 11.8

QUIZ Is this index primary or secondary? Explain! 11.9

Solution Is this index primary or secondary? A: Secondary, b/c the file is not physically sorted on the search key. But what is the search key (Name) has duplicates? 11.10

Secondary Index with duplicates Secondary index on salary field of instructor If the search key can have duplicates, we add another level of indirection: The index entry points to a bucket that contains pointers to all the physical records with that particular search-key value. 11.11

Ordered index: Dense Dense index There is an index record for every search-key value E.g.: Dense and primary index on ID attribute (PK) of instructor table 11.12

Ordered index: Dense E.g.: Dense and primary index on dept_name, with instructor file sorted on dept_name (not PK) 11.13

Ordered index: Sparse Sparse Index: contains index records for only some of the search-key values. It is applicable only as primary index, i.e. when the records are physically ordered on the search-key 11.14

Ordered index: Sparse Algorithm for locating a record with search-key value K: Find index record with largest search-key value < K Search the file sequentially starting at the record to which the index record points 11.15

Ordered index: Sparse Compared to dense indices, a sparse index: Requires less space and less maintenance overhead for insertions and deletions. It is slower for locating records, b/c it requires multiple accesses to the file. Good tradeoff: sparse index with an index entry for every block in file, corresponding to least search-key value in the block. 11.16

Quick review QUIZ What are the two main type of indices used in DBMS? 11.17

Solution What are the two main type of indices used in DBMS? Ordered index Hash index 11.18

Quick review QUIZ What are two classifications for ordered indices? 11.19

Solution What are two classifications for ordered indices? 1. Primary index (the one on which the physical file is sorted) vs. secondary index (not the one on which the physical file is sorted). 2. Dense index (contains all keys) vs. sparse index (not all keys are present). 11.20

QUIZ Which index is dense and which is sparse? Database Source: http://www.exploredatabase.com/2015/11/secondary-index-database-index.html System Concepts - 6 th Edition 11.21

Solution Which index is dense and which is sparse? Database Source: http://www.exploredatabase.com/2015/11/secondary-index-database-index.html System Concepts - 6 th Edition 11.22

QUIZ The index pictured is primary and sparse. Can there be secondary sparse indices? Give an example or explain why it s not possible. 11.23

Solution The index pictured is primary and sparse. Can there be secondary sparse indices? No, b/c if we searched for a key that s not in the index, it would be impossible to know where it was in the file! 11.24

QUIZ: Classify these indices as primary/secondary and dense/sparse? 11.25

QUIZ: Classify these indices as primary/secondary and dense/sparse Images source: http://webserver.ignou.ac.in/virtualcampus/bit_studymaterials/tri8/cst203-bl1-u3.htm 11.26

QUIZ: What is the difference between these secondary indices? 11.27

A: In the one on the right, the pointers are approximate they point to the correct block, but not to the actual record within the block 11.28

Performance of ordered indices Pro: substantial speed increase when searching for records. Con: when a table in the DB is modified, every index on that file(s) storing the table must be updated. Pro: Sequential scan using primary index is efficient Con: sequential scan using a secondary index is expensive Each record access may fetch a new block from disk Block fetch requires about 5 to 10 ms (HDD), versus 10-50 ns for main memory access (RAM) 11.29

11.2.2 Hierarchical/Multilevel Index For a large table, the primary index may not fit in main memory store it on disk access becomes expensive. Solution: treat the primary index, kept on disk, as a sequential file and construct a sparse index on it. outer index a sparse index of primary index inner index the primary index file 11.30

Two-level index 11.31

Hierarchical/Multilevel Index If even the outer index is too large to fit in main memory, yet another level of indexing can be created (three-level), and so on. Overhead is introduced: Indices at all levels must be updated on insertion or deletion of records in/from the file! 11.32

Index Update: Deletion Single-level index entry deletion: Dense indices deletion of search-key is similar to file record deletion. 11.33

Index Update: Deletion Single-level index entry deletion: Sparse indices? 11.34

Index Update: Deletion Single-level index entry deletion: Sparse indices if an entry for the search key exists in the index, it is deleted by replacing the entry in the index with the next search-key value in the file (in search-key order). If the next search-key value already has an index entry, the entry is deleted instead of being replaced. 11.35

Index Update: Insertion Single-level index insertion: Perform a lookup using the search-key value appearing in the record to be inserted. Dense indices if the search-key value does not appear in the index, insert it. Sparse indices if index stores an entry for each block of the file, no change needs to be made to the index unless a new block is created. If a new block is created, the first search-key value appearing in the new block is inserted into the index. Multilevel insertion and deletion: The algorithms are simple extensions of the single-level algorithms 11.36

Disadvantages of indexed-sequential files Performance of all operations degrades as file grows. Periodic reorganization of entire file is required E.g. insertion of a tuple requires either: Overflow block, or Shifting of all records following it 11.37 EOL 1

11.3 B + -Tree Index Files B + -tree indices are an alternative to indexed-sequential files. B + -tree is a type of balanced tree. a.k.a. skinny tree 11.38

11.3 B + -Tree Index Files Why do we need balanced trees? Most operations in a tree (search, insert, delete) are Big-Oh of the height 11.39

B + -Tree At most n 1 keys and n pointers in each node. (n = 4 here) Nodes may be only partially filled All leaves must be on the same level To avoid skinny trees, all nodes except the root and leaves must have at least n/2 keys. We say that the fill factor is at least 50%. Ceiling function Database Image System source: Concepts http://en.wikipedia.org/wiki/b%2b_tree - 6 th Edition 11.40

There are 3 types of pointers in a B + -Tree Those inside the tree point to other nodes of the tree. Horizontal from one leaf to the next Those in the leaves point to the actual tuple of data on the disk. Database Image System source: Concepts http://en.wikipedia.org/wiki/b%2b_tree - 6 th Edition 11.41

Redo the figure on the prev. slide to show the entire setup for the tree index, like this: 11.42

B + -Tree Node Structure The keys are logically in between the pointers The search-keys in a node are ordered K 1 < K 2 < K 3 <... < K n 1 (Initially assume no duplicate keys, address duplicates later) All keys x in the subtree pointed to by P i lie in between the two adjacent keys: K i-1 x < K i Sometimes we write informally: K i-1 P i < K i 11.43

Complete the hand-drawn figure on the prev. slide to include the left-most and right-most pointers, like this: 11.44

Completing the definition of B + -tree Each internal node (i.e. not root or leaf) has at least n/2 pointers (children). A leaf node has at least (n 1)/2 keys. Special cases: If the root is not a leaf, it has at least 2 children. If the root is a leaf (i.e. there are no other nodes in the tree!), there are no restrictions - it can have between 0 and (n 1) values. In many applications, the fill factor can be adjusted, even with separate values for leaves and internal nodes! 11.45

Leaf Nodes in B + -Trees Properties of a leaf node: For i = 1, 2,..., n 1, pointer P i points to a file record with search-key value K i, If L i, L j are leaf nodes and i < j, L i s search-key values are less than or equal to L j s search-key values P n points to next leaf node in search-key order 11.46

The previous slides contain all the formal requirements that a B+ tree must fulfill To do for next time: List on one page all the requirements (include in your memory sheet!) 11.47

B + tree example Find: The value of n The fill limit for the leaf nodes (# of keys) The fill limit for internal nodes (# of pointers/children) The fill limit for the root Is this a valid B+ tree? 11.48

B + tree example n = 6 (max # of pointers/children) Leaf nodes must have between at least 3 keys, acc. to fmla. (n 1)/2. Internal nodes must have between at least 3 children, acc. to fmla. n/2. Root must have at least 2 children, since it s not the only node in the tree. 11.49

Another B + tree example Find: The value of n The fill limit for the leaf nodes (# of keys) The fill limit for internal nodes (# of pointers/children) The fill limit for the root Is this a valid B+ tree? 11.50

B or B+ tree? Not in text B+ trees are B trees with two additional conditions: In B trees, it is allowed for pointers to records to be placed anywhere in the tree, whereas in B+ trees these pointers to data can only be placed in the leaves. B trees don t have the horizontal pointers from one leaf to the next. Food for thought: Why are these features better for the operation of a DBMS? 11.51

To find record with search-key value V: Queries on B + -Trees 1. C=root 2. While C is not a leaf node { 1. Let K i be the smallest key in C such that V K i. 2. If no such exists set C = last non-null pointer in C 3. Else if (V = K i ) set C = P i +1 4. Else set C = P i } //end while 3. Let K i be the smallest key in C such that K i = V 1. If there is such a value i, follow pointer P i to desired tuple on disk 2. Else no record with search-key value V exists. 11.52

QUIZ: Search for key 25 in this B+ tree..... 11.53

QUIZ: Search for key 85 in this B+ tree 11.54

QUIZ: Search for key 55 in this B+ tree 11.55

Remarks on B + -trees Since the inter-node connections are done by pointers, logically close blocks need not be physically close. The non-leaf levels of the B + -tree form a hierarchy of sparse indices. Insertions and deletions to the main file can be handled efficiently, as the index can be restructured in logarithmic time (next slides). 11.56

Remarks on B + -trees The B + -tree contains a relatively small number of levels Level below root has at least 2* n/2 values Next level has at least 2* n/2 * n/2 values.. etc. If there are K search-key values in the file, the length of the path (tree height + 1) is no more than log n/2 (K) Thus searches can be conducted efficiently. See pp.277-278 of Levitin s Algorithms 3 rd ed. for the complete derivation and the exact formula! 11.57

Efficiency of Queries on B +- Trees n is typically around 100 K = 1 million search key values Conclusion: L log 50 (1,000,000) = 4 tree nodes are accessed in a lookup. Plus another disk access to retrieve the data! B+ trees tend to be fat and short Contrast this with a balanced binary tree with 1 million search key values around 20 tree nodes are accessed in a lookup! 11.58

Your turn! Assume: K =10 million search key values Size of disk block = 8 KB 100 Bytes per entry (i.e. key + pointer together) n =?? Accessing each block on the HDD requires 5 ms Find and compare the time needed to access the data with: B+ tree index Binary tree index Sequential search of a non-indexed file Assume each key is part of a 256-Byte record. 11.59

Your turn! Assume: K =10 million search key values Size of disk block = 8 KB 100 Bytes per entry (i.e. key + pointer together) n = 8 KB / 100 Bytes 80 Accessing each block on the HDD requires 5 ms Find and compare the time needed to access the data with: B+ tree index Binary tree index Sequential search of a non-indexed file Assume each key is part of a 256-Byte record. 11.60

Your turn! Assume: K =10 million search key values Size of disk block = 8 KB 100 Bytes per entry (i.e. key + pointer together) n = 8 KB / 100 Bytes 80 Accessing each block on the HDD requires 5 ms Find and compare the time needed to access the data with: B+ tree index Binary tree index Sequential search of a non-indexed file Assume each key is part of a 256-Byte record. 11.61

Updates on B + -Trees: Insertion 1. Find the leaf node in which the search-key value would appear 2. If the search-key value is already present in the leaf node 1. Add record to the file (duplicate!) 2. If necessary add a pointer to the bucket. 3. If the search-key value is not present, then 1. add the record to the main file (and create a bucket if necessary) 2. If there is room in the leaf node, insert (key-value, pointer) pair in the leaf node 3. Otherwise, split the node (along with the new (key-value, pointer) entry) as discussed in the next slide. 11.62

Insertion may require splitting node(s) Splitting a leaf node: take the n (search-key value, pointer) pairs (including the one being inserted) in sorted order. Place the first n/2 in the original node, and the rest in a new node. let the new node be p, and let k be the least key value in p. Insert (k,p) in the parent of the node being split. If the parent is full, split it and propagate the split further up. Splitting of nodes proceeds upwards till a node that is not full is found. In the worst case the root node may be split increasing the height of the tree by 1. EXAMPLES 11.63

B + -Tree insertion example 1 How to split leaf nodes: 1. Split node containing Brandt, Califieri and Crick. 2. Insert the FIRST key in the RIGHT node (Califieri) into parent 11.64

B + -Tree insertion example 2 How to split non-leaf nodes: 1. Same as leaf nodes, but 2. The key propagating up (Gold) does not stay on the current level B + -Tree before and after insertion of Lamport 11.65

QUIZ: Insert keys 21, 22, 23 in this B+ tree 11.66

Read: 11.3.3.2 Deletion (Examples in the lab) 11.67

Ways to handle non-unique search keys 1. Store duplicate key only once in the tree, and create bucket of duplicates as separate blocks. Problems: How to deal with variable-sized buckets? What to do when a bucket becomes full? (Chain of buckets?) How to delete from buckets? 11.68

Ways to handle non-unique search keys 2. Make search key unique by adding a unique recordidentifier, a.k.a. an uniquifier attribute Extra storage overhead for keys Simpler code for insertion/deletion Widely used What support does PostgreSQL offer for uniquifiers? 11.69

See PostgreSQL lab: SERIAL data type! CREATE SEQUENCE test_seq nextval('test_seq'); -- Increments the value of the specified sequence and returns the new value (as an integer) currval('test_seq'); -- Returns the value returned by the most recent nextval(). If nextval() hasn't been used yet, an error is returned. setval('test_seq', n); -- Sets the current value of the sequence to n. DROP SEQUENCE test_seq 11.70

Conclusion on B + -Tree Index Files Advantages of B + -tree index files: automatically reorganizes itself with small, local, changes, in the face of insertions and deletions. Reorganization of entire file is not required to maintain performance. (Minor) disadvantage of B + -trees: extra insertion and deletion overhead, space overhead. Advantages of B + -trees outweigh disadvantages B + -trees are used extensively 11.71

SKIP sections 11.4 and 11.5 EoL2 11.72

QUIZ: Definition of B+ trees What is n in this tree? Is this a valid B+ tree? (Verify all conditions!) 11.73

QUIZ: Definition of B+ trees What is n in this tree? n = 4 Is this a valid B+ tree? Yes, all conditions are satisfied! 11.74

QUIZ: Insertion in B+ trees Insert 12. Source: http://www.cburch.com/cs/340/reading/btree/ 11.75

QUIZ: Insertion in B+ trees Insert 12. Source: http://www.cburch.com/cs/340/reading/btree/ 11.76

QUIZ: Insertion in B+ trees Insert 12. Source: http://www.cburch.com/cs/340/reading/btree/ 11.77

QUIZ: Insertion in B+ trees Insert 12. Source: http://www.cburch.com/cs/340/reading/btree/ 11.78

QUIZ We studied two types on indices so far: ordered and B+ tree. Draw a Venn diagram representing the two! 11.79

11.6 Hashing Basic ideas: Tree indices are efficient (L log n/2 (N) ) and mathematically well-understood, but When querying for individual tuples we have too much precision: although we need only one tuple, reading from the HDD is still done in entire blocks (~4KB), each of which usually stores multiple tuples. The parable of the two storage cabinets 11.80

One little drawer for each item Larger drawers, with multiple items in each Database Image source: System Concepts www.quantum-bits.com - 6 th Edition 11.81

Static Hashing Bucket = unit of storage containing one or more records (typically a disk block). Hash file organization: we obtain the bucket of a record directly from its search-key value using a hash function. Hash function h is a function from the set of all search-key values K to the set of all bucket addresses B. Hash function is used to locate records for query, insertion and deletion. Records w/different search-key values will be mapped to same bucket entire bucket is searched sequentially to locate a record. 11.82

Example of Hash File Organization File stores instructor table, using dept_name as key (See figure in next slide.) There are 8 buckets The binary representation of the ith character is assumed to be the integer i. The hash function returns the sum of the binary representations of the characters modulo 8 E.g. h(music) = 1 h(history) = 2 h(physics) = 3 h(elec. Eng.) = 3 11.83

11.84

EXAMPLE: Hash functions in Python The hash function returns the sum of the binary representations of the characters modulo 8 E.g. h(music) = 1 h(history) = 2 h(physics) = 3 h(elec. Eng.) = 3 Write in Python the function h(string) described Hints: The Python library function ord() returns the ASCII code of its character argument The modulus is implemented as the operator % 11.85

11.86

Hash Functions Worst case: hash function maps all search-key values to same bucket; this makes access time proportional to the number of search-key values in the file. Ideal hash function is uniform each bucket is assigned the same average number of search-key values from the set of all possible values. Ideal hash function is random, so each bucket will have the same number of records assigned to it irrespective of the actual distribution of search-key values in the file. To achieve (pseudo) randomness, typical hash functions perform computations on the internal binary representation of the search-key, as in the prev. example. 11.87

What to do when a bucket becomes full? 11.88

Handling of Bucket Overflows Bucket overflow can occur because of Insufficient buckets Skew in distribution of records two reasons: multiple records have same search-key value chosen hash function produces non-uniform distribution of key values Although the probability of bucket overflow can be reduced, it cannot be eliminated; it is handled by using overflow buckets. 11.89

Overflow chaining the overflow buckets of a given bucket are chained together in a linked list. This is called closed hashing. An alternative exists, called open hashing, which does not use overflow buckets. Not suitable for DB apps.! E.g. linear probing 11.90

Hash Indices Hashing can be used not only for file organization, but also for index-structure creation. A hash index organizes the search keys, with their associated record pointers, into a hash file structure. Strictly speaking, hash indices are always secondary indices if the file itself is organized using hashing, a separate primary hash index on it using the same search-key is unnecessary. However, we use the term hash index to refer to both secondary index structures and hash organized files. 11.91

Example of Hash Index Hash index on instructor.id 11.92

Deficiencies of Static Hashing Function h maps search-key values to a fixed set of B of bucket addresses. Databases grow or shrink with time. If initial number of buckets is too small, and file grows, performance will degrade due to too much overflows. If space is allocated for anticipated growth, a significant amount of space will be wasted initially (and buckets will be underfull). If database shrinks, again space will be wasted. One solution: periodic re-organization of the file with a new hash function Expensive, disrupts normal operations Better solution: allow the number of buckets to be modified dynamically. 11.93

11.7 Dynamic Hashing Good for DBs that grow and shrink in size Allows the hash function to be modified dynamically Extendable hashing is one form of dynamic hashing 11.94

Dynamic Hashing: Extendable hashing Hash function generates values over a large range, typically b-bit integers, with b = 32. At any time use only a prefix of the hash function to index into a table of bucket addresses. Let the length of the prefix be i bits, 0 i 32. Bucket address table size = 2 i. Initially i = 0 Value of i grows and shrinks as the table grows and shrinks. Multiple entries in the bucket address table may point to the same bucket (why?) Thus, actual # of buckets is < 2 i The # of buckets also changes dynamically due to merging and splitting of buckets. 11.95

Extendable Hash Structure In this structure, i 2 = i 3 = i, whereas i 1 = i 1 (see next slide for details) 11.96

Use of Extendable Hash Structure Each bucket j stores a value i j All the entries that point to the same bucket have the same values on the first i j bits. To locate the bucket containing search-key K j : 1. Compute h(k j ) = X 2. Use the first i high order bits of X as a displacement into bucket address table, and follow the pointer to appropriate bucket To insert a record with search-key value K j follow same procedure as look-up and locate the bucket, say j. If there is room in the bucket j insert record in the bucket. Else the bucket must be split and insertion re-attempted (next slide.) Overflow buckets used instead in some cases 11.97

Insertion in Extendable Hash Structure To split a bucket j when inserting record with search-key value K j : If i > i j (more than one pointer to bucket j) allocate a new bucket z, and set i j = i z = (i j + 1) Update the second half of the bucket address table entries originally pointing to j, to point to z remove each record in bucket j and reinsert (in j or z) recompute new bucket for K j and insert record in the bucket (further splitting is required if the bucket is still full) If i = i j (only one pointer to bucket j) If i reaches some limit b, or too many splits have happened in this insertion, create an overflow bucket Else increment i and double the size of the bucket address table. replace each entry in the table by two entries that point to the same bucket. recompute new bucket address table entry for K j Now i > i j so use the first case above. 11.98

Use of Extendable Hash Structure: Example 11.99

Example (Cont.) Initial Hash structure; bucket size = 2 11.100

Example (Cont.) Hash structure after insertion of Mozart, Srinivasan, and Wu records 11.101

Example (Cont.) Hash structure after insertion of Einstein record 11.102

Example (Cont.) Hash structure after insertion of Gold and El Said records 11.103

Your turn! Insert (Katz, Comp.Sci.) record. 11.104

Example (Cont.) Hash structure after insertion of Katz record 11.105

Example (Cont.) And after insertion of 4 more records 11.106

Example (Cont.) And after insertion of Kim record in previous hash structure 11.107

Hashing pros and cons Benefits of extendable hashing: Hash performance does not degrade with growth of file Minimal space overhead Disadvantages of extendable hashing Extra level of indirection to find desired record Bucket address table may itself become very big (larger than memory) Cannot allocate very large contiguous areas on disk either Solution: B + -tree structure to locate desired record in bucket address table Changing size of bucket address table is an expensive operation Linear hashing is an alternative mechanism Allows incremental growth of its directory (equivalent to bucket address table) at the cost of more bucket overflows. 11.108

SKIP 11.8, 11.9 11.109

11.10 Index definition in SQL Note: In keeping with the declarative nature of SQL, there is no standard way provided to specify what type of index, or any other index details. 11.110

Index definition in PostgreSQL PostgreSQL provides several index types: B-tree, Hash, GiST, SP-GiST and GIN. Each index type uses a different algorithm that is best suited to different types of queries. By default, the CREATE INDEX command creates B+ tree indexes, which fit the most common situations. 11.111

What we covered in Chapter 12: Basic Concepts Ordered Indices B + Tree Indices 11.4 B+ Tree Extensions 11.5 Multiple-Key Access Static Hashing Dynamic Hashing 11.8 Comparison of Ordered Indexing and Hashing 11.9 Bitmap indices Index definition in SQL 11.112

Homework for Ch.11: 3, 4, 6, 15, 16, 17, 20, 22 11.113