index and hashing manual and presentation foe students
TRANSCRIPT
-
7/27/2019 Index and Hashing manual and presentation foe students
1/96
Silberschatz, Korth and Sudarshan12. 1 Database System Concepts
Chapter 12: Indexing and HashingBasic Concepts
Ordered IndicesB+-Tree Index Files
B-Tree Index Files
Static Hashing
Dynamic HashingComparison of Ordered Indexing and Hashing
Index Definition in SQL
Multiple-Key Access
-
7/27/2019 Index and Hashing manual and presentation foe students
2/96
Silberschatz, Korth and Sudarshan12. 2 Database System Concepts
Data Dictionary Storage
Information about relationsnames of relationsnames and types of attributes of each relationnames and definitions of viewsintegrity constraints
User and accounting information, including passwordsStatistical and descriptive data
number of tuples in each relation
Physical file organization informationHow relation is stored (sequential/hash/) Physical location of relation
Information about indices (Chapter 12)
Data dictionary (also called system catalog ) stores metadata :
that is, data about data, such as
-
7/27/2019 Index and Hashing manual and presentation foe students
3/96
Silberschatz, Korth and Sudarshan12. 3 Database System Concepts
Data Dictionary Storage (Cont.)Catalog structure
Relational representation on diskspecialized data structures designed for efficient access, in memory
A possible catalog representation:
Relation_metadata = (relation_name, number_of_attributes,storage_organization, location )
Attribute_metadata = (attribute_name, relation_name, domain_type, position, length )
User_metadata = (user_name, encrypted_password, group )
Index_metadata = (index_name, relation_name, index_type,index_attributes )View_metadata = (view_name, definition )
-
7/27/2019 Index and Hashing manual and presentation foe students
4/96
Silberschatz, Korth and Sudarshan12. 4 Database System Concepts
Indexing: Basic ConceptsIndexing mechanisms are used to speed up access to desireddata.
E.g., author catalog in library
Search Key - attribute to set of attributes used to look uprecords in a file.
An index file consists of records (called index entries ) of the
form
Index files are typically much smaller than the original file
Two basic kinds of indices:Ordered indices: search keys are stored in sorted order
Hash indices: search keys are distributed uniformly acrossbuckets using a hash function .
search-key pointer
-
7/27/2019 Index and Hashing manual and presentation foe students
5/96
Silberschatz, Korth and Sudarshan12. 5 Database System Concepts
Basic concepts (Cont.)Index definition: Index is a file whose records (entries) have the
following structure:(search-key, pointer or set of pointers to data records ).
When the search key is unique the index has fixed size records,otherwise it may have variable size records.
What is the pointer?Block number or RID!
-
7/27/2019 Index and Hashing manual and presentation foe students
6/96
Silberschatz, Korth and Sudarshan12. 6 Database System Concepts
Index Evaluation MetricsAccess types supported efficiently. E.g.,
records with a specified value in the attributeor records with an attribute value falling in a specified range ofvalues.
Access time
Insertion timeDeletion time
Space overhead
-
7/27/2019 Index and Hashing manual and presentation foe students
7/96 Silberschatz, Korth and Sudarshan12. 7 Database System Concepts
Ordered Indices
In an ordered index , index entries are stored sorted on thesearch key value. E.g., author catalog in library.
Primary index : in a sequentially ordered file, the index whosesearch key specifies the sequential order of the file.
Also called clustering index
The search key of a primary index is usually but not necessarily theprimary key.
Secondary index : an index whose search key specifies an orderdifferent from the sequential order of the file. Also callednon-clustering index .
Index-sequential file : ordered sequential file with a primary index.
Indexing techniques evaluated on basis of:
-
7/27/2019 Index and Hashing manual and presentation foe students
8/96 Silberschatz, Korth and Sudarshan12. 8 Database System Concepts
Classes of Indexes
Unique/non-unique whether search key is unique/non-uniqueDense/Nondense every/not every search key (every record for Uniquekey) in the data file has a corresponding pointer in the index.
Clustered/Nonclustered order of index search key is equal/not equal tofile order.
Primary/Secondary search key equal/not equal to primary key. Also,the answer is a single/set of data file records.
Note difference in definition of Primary index (us vs. Silberschatz)
Note: for Unique key Dense index indexes every record, Non-densedoes not index every record
Note: Non-dense index must be clustered!
-
7/27/2019 Index and Hashing manual and presentation foe students
9/96 Silberschatz, Korth and Sudarshan12. 9 Database System Concepts
Dense Clustered Index FileDense index Index record appears for every search-key value
in the file. (note, for every search key vs. for every record)
-
7/27/2019 Index and Hashing manual and presentation foe students
10/96 Silberschatz, Korth and Sudarshan12. 10 Database System Concepts
Sparse Index FilesSparse Index : contains index records for only some search-key
values.Applicable when records are sequentially ordered on search-key
To locate a record with search-key value K we:Find index record with largest search-key value < K
Search file sequentially starting at the record to which the indexrecord points
Less space and less maintenance overhead for insertions anddeletions.
Generally slower than dense index for locating records.
Good tradeoff: sparse index with an index entry for every block infile, corresponding to least search-key value in the block.
Basis of the ISAM index
-
7/27/2019 Index and Hashing manual and presentation foe students
11/96 Silberschatz, Korth and Sudarshan12. 11 Database System Concepts
Example of Sparse Clustered Index File
-
7/27/2019 Index and Hashing manual and presentation foe students
12/96 Silberschatz, Korth and Sudarshan12. 12 Database System Concepts
Multilevel IndexIf primary index does not fit in memory, access becomes
expensive.To reduce number of disk accesses to index records, treatprimary index kept on disk as a sequential file and construct asparse index on it.
outer index a sparse index of primary index
inner index the primary index file
If even outer index is too large to fit in main memory, yet anotherlevel of index can be created, and so on.
Indices at all levels must be updated on insertion or deletion from
the file.
-
7/27/2019 Index and Hashing manual and presentation foe students
13/96 Silberschatz, Korth and Sudarshan12. 13 Database System Concepts
Multilevel Index (Cont.)
-
7/27/2019 Index and Hashing manual and presentation foe students
14/96 Silberschatz, Korth and Sudarshan12. 14 Database System Concepts
A two level primary Non-dense clustered index resemblingIsam
-
7/27/2019 Index and Hashing manual and presentation foe students
15/96 Silberschatz, Korth and Sudarshan12. 15 Database System Concepts
Index Update: DeletionIf deleted record was the only record in the file with its particular
search-key value, the search-key is deleted from the index also.Single-level index deletion:
Dense indices deletion of search-key is similar to file recorddeletion.
Sparse indices if an entry for the search key exists in the index, itis 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-keyvalue already has an index entry, the entry is deleted instead ofbeing replaced.
-
7/27/2019 Index and Hashing manual and presentation foe students
16/96 Silberschatz, Korth and Sudarshan12. 16 Database System Concepts
Index Update: InsertionSingle-level index insertion:
Perform a lookup using the search-key value appearing in therecord to be inserted.
Dense indices if the search-key value does not appear in theindex, 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 iscreated. In this case, the first search-key value appearing in thenew block is inserted into the index.
Multilevel insertion (as well as deletion) algorithms are simpleextensions of the single-level algorithms
-
7/27/2019 Index and Hashing manual and presentation foe students
17/96 Silberschatz, Korth and Sudarshan12. 17 Database System Concepts
Secondary Indices
Frequently, one wants to find all the records whosevalues in a certain field (which is not the search-key ofthe primary index satisfy some condition.
Example 1: In the account database stored sequentiallyby account number, we may want to find all accounts in aparticular branch
Example 2: as above, but where we want to find allaccounts with a specified balance or range of balances
We can have a secondary index with an index recordfor each search-key value; index record points to abucket that contains pointers to all the actual recordswith that particular search-key value.
-
7/27/2019 Index and Hashing manual and presentation foe students
18/96 Silberschatz, Korth and Sudarshan12. 18 Database System Concepts
Primary and Secondary IndicesSecondary indices have to be dense.
Indices offer substantial benefits when searching for records.When a file is modified, every index on the file must be updated,Updating indices imposes overhead on database modification.
Sequential scan using primary index is efficient, but a sequentialscan using a secondary index is expensive
each record access may fetch a new block from disk since index isusually un-clustered
D U l d S d I d
-
7/27/2019 Index and Hashing manual and presentation foe students
19/96 Silberschatz, Korth and Sudarshan12. 19 Database System Concepts
Dense Unclustered Secondary Indexon balance field of account- Access List
-
7/27/2019 Index and Hashing manual and presentation foe students
20/96 Silberschatz, Korth and Sudarshan12. 20 Database System Concepts
B+-Tree Index Files
All paths from root to leaf are of the same length
Each node that is not a root or a leaf has between [ n /2] andn children.
A leaf node has between [( n 1)/2] and n 1 values
Special cases:If the root is not a leaf, it has at least 2 children.
If the root is a leaf (that is, there are no other nodes in thetree), it can have between 0 and ( n 1) values.
A B+-tree is a rooted tree satisfying the following properties:
-
7/27/2019 Index and Hashing manual and presentation foe students
21/96 Silberschatz, Korth and Sudarshan12. 21 Database System Concepts
B+-Tree Node StructureTypical node
Ki are the search-key values
P i are pointers to children (for non-leaf nodes) or pointers to records
or buckets of records (for leaf nodes).The search-keys in a node are ordered
K 1 < K 2 < K 3 < . . . < K n 1
-
7/27/2019 Index and Hashing manual and presentation foe students
22/96 Silberschatz, Korth and Sudarshan12. 22 Database System Concepts
Leaf Nodes in B +-Trees
For i = 1, 2, . . ., n 1, pointer P i either points to a file record withsearch-key value K i , or to a bucket of pointers to file records,each record having search-key value K i . Only need bucketstructure if search-key does not form a primary key.
If Li , L j are leaf nodes and i < j, L i s search -key values are less
than L j s search -key valuesP n points to next leaf node in search-key order
Properties of a leaf node:
-
7/27/2019 Index and Hashing manual and presentation foe students
23/96 Silberschatz, Korth and Sudarshan12. 23 Database System Concepts
Non-Leaf Nodes in B +-TreesNon leaf nodes form a multi-level sparse index on the leaf nodes.
For a non-leaf node with m pointers:All the search-keys in the subtree to which P 1 points are less thanK 1
For 2 i n 1, all the search-keys in the subtree to which P i pointshave values greater than or equal to K i 1 and less than K i
P n points to the subtree with keys greater than K n 1 and less than thefirst key in next leaf
-
7/27/2019 Index and Hashing manual and presentation foe students
24/96
Silberschatz, Korth and Sudarshan12. 24 Database System Concepts
-
7/27/2019 Index and Hashing manual and presentation foe students
25/96
Silberschatz, Korth and Sudarshan12. 25 Database System Concepts
-Key)
B+-tree for account file (n = 3)
Note, index points to FIRST key!
-
7/27/2019 Index and Hashing manual and presentation foe students
26/96
Silberschatz, Korth and Sudarshan12. 26 Database System Concepts
Example of B +-tree
Leaf nodes must have between 2 and 4 values( (n 1)/2 and n 1, with n = 5).
Non-leaf nodes other than root must have between 3and 5 children ( (n /2 and n with n =5).
Root must have at least 2 children.
B+-tree for account file (n= 5)
-
7/27/2019 Index and Hashing manual and presentation foe students
27/96
Silberschatz, Korth and Sudarshan12. 27 Database System Concepts
Observations about B +-treesSince 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 sparseindices.
The B +-tree contains a relatively small number of levels(logarithmic in the size of the main file), thus searches can beconducted efficiently.Insertions and deletions to the main file can be handledefficiently, as the index can be restructured in logarithmic time(as we shall see).
Differences between B+ and B TreeDifferences between B-tree Index and B-tree file
-
7/27/2019 Index and Hashing manual and presentation foe students
28/96
Silberschatz, Korth and Sudarshan12. 28 Database System Concepts
Queries on B +-TreesFind all records with a search-key value of k.1. Start with the root node
1. Examine the node for the smallest search-key value > k.
2. If such a value exists, assume it is K j . Then follow P i to thechild node
3. Otherwise k K m 1, where there are m pointers in the
node. Then follow P m to the child node.2. If the node reached by following the pointer above is not a leaf
node, repeat the above procedure on the node, and follow thecorresponding pointer.
3. Eventually reach a leaf node. If for some i , key K i = k followpointer P
i to the desired record or bucket. Else no record with
search-key value k exists.
-
7/27/2019 Index and Hashing manual and presentation foe students
29/96
Silberschatz, Korth and Sudarshan12. 29 Database System Concepts
Queries on B +-Trees (Cont.)In processing a query, a path is traversed in the tree fromthe root to some leaf node.
If there are K search-key values in the file, the path is nolonger than log n /2 (K ) .
A node is generally the same size as a disk block,typically 4 kilobytes, and n is typically around 100 (40
bytes per index entry).With 1 million search key values and n = 100, at mostlog 50(1,000,000) = 4 nodes are accessed in a lookup.
Contrast this with a balanced binary free with 1 millionsearch key values around 20 nodes are accessed in alookup
above difference is significant since every node accessmay need a disk I/O, costing around 20 milliseconds!
-
7/27/2019 Index and Hashing manual and presentation foe students
30/96
Silberschatz, Korth and Sudarshan12. 30 Database System Concepts
Updates on B +-Trees: InsertionFind the leaf node in which the search-key value would appear
If the search-key value is already there in the leaf node, record isadded to file and if necessary a pointer is inserted into thebucket.
If the search-key value is not there, then add the record to themain file and create a bucket if necessary. Then:
If there is room in the leaf node, insert (key-value, pointer) pair in theleaf node
Otherwise, split the node (along with the new (key-value, pointer)entry) as discussed in the next slide.
-
7/27/2019 Index and Hashing manual and presentation foe students
31/96
Silberschatz, Korth and Sudarshan12. 31 Database System Concepts
Updates on B +-Trees: Insertion (Cont.)Splitting a node:
take the n(search-key value, pointer) pairs (including the one beinginserted) 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 itand propagate the split further up.
The splitting of nodes proceeds upwards till a node that is not fullis found. In the worst case the root node may be split increasingthe height of the tree by 1.
Result of splitting node containing Brighton and Downtown oninserting Clearview
U d B + T I i (C )
-
7/27/2019 Index and Hashing manual and presentation foe students
32/96
Silberschatz, Korth and Sudarshan12. 32 Database System Concepts
Updates on B +-Trees: Insertion (Cont.)
B+-Tree before and after insertion of Clearview
-i AS k )
-
7/27/2019 Index and Hashing manual and presentation foe students
33/96
Silberschatz, Korth and Sudarshan12. 33 Database System Concepts
points to LAST key)
-
7/27/2019 Index and Hashing manual and presentation foe students
34/96
Silberschatz, Korth and Sudarshan12. 34 Database System Concepts
Updates on B +-Trees: DeletionFind the record to be deleted, and remove it from themain file and from the bucket (if present)Remove (search-key value, pointer) from the leaf nodeif there is no bucket or if the bucket has become emptyIf the node has too few entries due to the removal, andthe entries in the node and a sibling fit into a singlenode, then
Insert all the search-key values in the two nodes into asingle node (the one on the left), and delete the othernode.Delete the pair ( K i 1, P i ), where P i is the pointer to thedeleted node, from its parent, recursively using the
above procedure.
-
7/27/2019 Index and Hashing manual and presentation foe students
35/96
Silberschatz, Korth and Sudarshan12. 35 Database System Concepts
Updates on B +-Trees: DeletionOtherwise, if the node has too few entries due to the removal,
and the entries in the node and a sibling do not fit into a singlenode, then Redistribute the pointers between the node and a sibling such that
both have more than the minimum number of entries.
Update the corresponding search-key value in the parent of the
node.The node deletions may cascade upwards till a node which hasn/2 or more pointers is found. If the root node has only one
pointer after deletion, it is deleted and the sole child becomes theroot.
E l f B + T D l ti
-
7/27/2019 Index and Hashing manual and presentation foe students
36/96
Silberschatz, Korth and Sudarshan12. 36 Database System Concepts
Examples of B +-Tree Deletion
The removal of the leaf node containing Downtown did notresult in its parent having too little pointers. So the cascadeddeletions stopped with the deleted leaf nodes parent.
Before and after deleting Downtown
-
7/27/2019 Index and Hashing manual and presentation foe students
37/96
Silberschatz, Korth and Sudarshan12. 37 Database System Concepts
Examples of B +-Tree Deletion (Cont.)
Node with Perryridge becomes underfull (actually empty, in this special case)and merged with its sibling.
As a result Perryridge nodes parent became underfull, and was merged with itssibling (and an entry was deleted from their parent)Root node then had only one child, and was deleted and its child became the new
root node
Deletion of Perryridge from result of previous example
-
7/27/2019 Index and Hashing manual and presentation foe students
38/96
Silberschatz, Korth and Sudarshan12. 38 Database System Concepts
Example of B +-tree Deletion (Cont.)
Parent of leaf containing Perryridge became underfull, and borrowed apointer from its left sibling
Search- key value in the parents parent changes as a result
Before and after deletion of Perryridge from earlier example
-
7/27/2019 Index and Hashing manual and presentation foe students
39/96
-
7/27/2019 Index and Hashing manual and presentation foe students
40/96
-
7/27/2019 Index and Hashing manual and presentation foe students
41/96
Silberschatz, Korth and Sudarshan12. 41 Database System Concepts
B+-Tree File Organization
Index file degradation problem is solved by using B +-Treeindices. Data file degradation problem is solved by using B +-Tree File Organization.
The leaf nodes in a B +-tree file organization store records,instead of pointers.
Since records are larger than pointers, the maximum number ofrecords that can be stored in a leaf node is less than the numberof pointers in a nonleaf node.
Leaf nodes are still required to be half full.
Insertion and deletion are handled in the same way as insertion
and deletion of entries in a B +-tree index.Simplest to implement sequential file organization no need for
overflows!
-
7/27/2019 Index and Hashing manual and presentation foe students
42/96
Silberschatz, Korth and Sudarshan12. 42 Database System Concepts
B+-Tree File Organization (Cont.)
Good space utilization important since records use more space thanpointers.To improve space utilization, involve more sibling nodes in redistributionduring splits and merges
Involving 2 siblings in redistribution (to avoid split / merge where possible)results in each node having at least entries
Example of B +-tree File Organization
3/2n
-
7/27/2019 Index and Hashing manual and presentation foe students
43/96
Silberschatz, Korth and Sudarshan12. 43 Database System Concepts
B-Tree Index FilesSimilar to B+-tree, but B-tree allows search-key values toappear only once; eliminates redundant storage of searchkeys.
Search keys in nonleaf nodes appear nowhere else in the B-tree; an additional pointer field for each search key in anonleaf node must be included.
Generalized B-tree leaf node
Nonleaf node pointers Bi are the bucket or file recordpointers.
B Tree Index File Example
-
7/27/2019 Index and Hashing manual and presentation foe students
44/96
Silberschatz, Korth and Sudarshan12. 44 Database System Concepts
B-Tree Index File Example
B-tree (above) and B+-tree (below) on same data
-
7/27/2019 Index and Hashing manual and presentation foe students
45/96
Silberschatz, Korth and Sudarshan12. 45 Database System Concepts
B-Tree Index Files (Cont.)Advantages of B-Tree indices:
May use less tree nodes than a corresponding B +-Tree.
Sometimes possible to find search-key value before reaching leaf node.
Disadvantages of B-Tree indices : Only small fraction of all search-key values are found early
Non-leaf nodes are larger, so fan-out is reduced (because of the extra pointer!).Thus B-Trees typically have greater depth than corresponding B +-Tree
Insertion and deletion more complicated than in B +-Trees
Implementation is harder than B +-Trees.
Reading in sorted order is hard
Typically, advantages of B-Trees do not out weigh disadvantages .
-
7/27/2019 Index and Hashing manual and presentation foe students
46/96
Silberschatz, Korth and Sudarshan12. 46 Database System Concepts
Assume a file with 10**5 records, a key is 8 bytes, a pointer is 4bytes, a block (page) is 1K. Compute time to access a singlerecord via index or a range of 1000 recordsNumber of entries in a node: 1024/12 = 85 lets round to 80.meaning 2d = 80, d =40 (we dont distinguish between number of pointers and number of keys (-1 ) with large numbers)
With 3 levels we can store at least 2*40**2 keys and at most wecan store upto 80**3, so we need h=3. In average we need about47 keys per node (lets round to 50)
Assuming root is in memory we need 2+1 page accesses to get toa record
To access 1000records we need 2 to get to the first leave +20leaves. Then depending whether the file is clustered on this indexor not:
Clustered: 22 + number of blocks to store 1000 records (need tocompute)
Unclustered: 1022
B+-tree Example computation
B+ trees Implementations issues
-
7/27/2019 Index and Hashing manual and presentation foe students
47/96
Silberschatz, Korth and Sudarshan12. 47 Database System Concepts
B -trees Implementations issues
Fixed vs. variable size keys.
Internal search (sequential, binary, jump).
Key compression.
Secondary index implementation (Access list vs. compositekeys).
Bulk loading.
-
7/27/2019 Index and Hashing manual and presentation foe students
48/96
Silberschatz, Korth and Sudarshan12. 48 Database System Concepts
Both direct and sequential access, including Range queries.
Always Balanced2-3 page accesses even for very large files.
At least 50% storage utilization and in average 70%
Dynamic, no need for Reorganization.
B+-tree Advantages
-
7/27/2019 Index and Hashing manual and presentation foe students
49/96
Silberschatz, Korth and Sudarshan12. 49 Database System Concepts
Memory based Hashing
1) Hash function maps key space to a smaller address space address = H(Key)
2) Collision resolution required to handle two keys hashed intothe same address
M b d H hi C lli i
-
7/27/2019 Index and Hashing manual and presentation foe students
50/96
Silberschatz, Korth and Sudarshan12. 50 Database System Concepts
Memory based Hashing CollisionResolution techniques
1) Linear overflow or open addressing find first empty slot andinsert.
2) Independent or chained overflow create overflow chains inoverflow areas.
-
7/27/2019 Index and Hashing manual and presentation foe students
51/96
Silberschatz, Korth and Sudarshan12. 51 Database System Concepts
-
7/27/2019 Index and Hashing manual and presentation foe students
52/96
-
7/27/2019 Index and Hashing manual and presentation foe students
53/96
Silberschatz, Korth and Sudarshan12. 53 Database System Concepts
Linear overflowP = n/(m-n) (1 for m=1.5n)
Clearly when n approaches m performance of linear overflow ismuch worse!
For loading factor 0.9 (n = 0.9m) p = 5 ! (avg. of 5 overflowrecords per hash!)
-
7/27/2019 Index and Hashing manual and presentation foe students
54/96
Silberschatz, Korth and Sudarshan12. 54 Database System Concepts
Disk based Static Hashing
A bucket is a unit of storage containing one or more records (a
bucket is typically a disk block).In a hash file organization we obtain the bucket of a recorddirectly from its search-key value using a hash function.
Hash function h is a function from the set of all search-keyvalues K to the set of all bucket addresses B.
Hash function is used to locate records for access, insertion aswell as deletion.
Records with different search-key values may be mapped tothe same bucket; thus entire bucket has to be searched
sequentially to locate a record.
k b d h h
-
7/27/2019 Index and Hashing manual and presentation foe students
55/96
Silberschatz, Korth and Sudarshan12. 55 Database System Concepts
Disk based Hashing - Hash FunctionsWorst hash function maps all search-key values to the samebucket; this makes access time proportional to the number of
search-key values in the file.An ideal hash function is uniform , i.e., each bucket is assignedthe same number of search-key values from the set of all possible values.
Ideal hash function is random , so each bucket will have thesame number of records assigned to it irrespective of the actual distribution of search-key values in the file.
Typical hash functions perform computation on the internalbinary representation of the search-key.
For example, for a string search-key, the binary representations ofall the characters in the string could be added and the sum modulothe number of buckets could be returned. .
-
7/27/2019 Index and Hashing manual and presentation foe students
56/96
l f h l ( )
-
7/27/2019 Index and Hashing manual and presentation foe students
57/96
Silberschatz, Korth and Sudarshan12. 57 Database System Concepts
Example of Hash File Organization (Cont.)
There are 10 buckets,
The binary representation of the I-th character is assumed to
be the integer i. The hash function returns the sum of the binaryrepresentations of the characters modulo 10
E.g. h(Perryridge) = 5 h(Round Hill) = 3 h(Brighton) = 3
Hash file organization of account file, using branch-name as key(See figure in next slide.)
-
7/27/2019 Index and Hashing manual and presentation foe students
58/96
H dli f B k O fl
-
7/27/2019 Index and Hashing manual and presentation foe students
59/96
Silberschatz, Korth and Sudarshan12. 59 Database System Concepts
Handling of Bucket OverflowsBucket overflow can occur because of
Insufficient buckets
Skew in distribution of records. This can occur due to tworeasons:
multiple records have same search-key value
chosen hash function produces non-uniform distribution of keyvalues
Although the probability of bucket overflow can be reduced, itcannot be eliminated; it is handled by using overflow buckets .
Handling of Bucket Overflows (Cont.)
-
7/27/2019 Index and Hashing manual and presentation foe students
60/96
Silberschatz, Korth and Sudarshan12. 60 Database System Concepts
a d g o Buc et Ove ows (Co t.)
Overflow chaining the overflow buckets of a given bucket arechained together in a linked list.
Above scheme is called closed hashing . An alternative, called open hashing , which does not use overflowbuckets, is not suitable for database applications.
-
7/27/2019 Index and Hashing manual and presentation foe students
61/96
Silberschatz, Korth and Sudarshan12. 61 Database System Concepts
P f f di k b d H hi
-
7/27/2019 Index and Hashing manual and presentation foe students
62/96
Silberschatz, Korth and Sudarshan12. 62 Database System Concepts
Performance of disk-based Hashing
Searching within a bucket
does not cost I/O!
H h I di
-
7/27/2019 Index and Hashing manual and presentation foe students
63/96
Silberschatz, Korth and Sudarshan12. 63 Database System Concepts
Hash IndicesHashing can be used not only for file organization, but also for index-structure creation.
A hash index organizes the search keys, with their associated recordpointers, into a hash file structure.
Strictly speaking, hash indices are always secondary indicesif the file itself is organized using hashing, a separate primary hash index onit using the same search-key is unnecessary.
However, we use the term hash index to refer to both secondary indexstructures and hash organized files.
I dont agree ! You may have Hash index as primary and the file is clusteredon another key or a Heap file
Note the difference between a Hash Index and a Hash file whether thebuckets contain Pointers to data records or the records themselves! (sameas difference between A B+-tree index and a B+-tree file! )
E l f H h I d
-
7/27/2019 Index and Hashing manual and presentation foe students
64/96
Silberschatz, Korth and Sudarshan12. 64 Database System Concepts
Example of Hash Index
Deficiencies of Static Hashing
-
7/27/2019 Index and Hashing manual and presentation foe students
65/96
Silberschatz, Korth and Sudarshan12. 65 Database System Concepts
Deficiencies of Static HashingIn static hashing, function h maps search-key values to a fixedset of B of bucket addresses.
Databases grow with time. If initial number of buckets is too small,performance will degrade due to too much overflows.
If file size at some point in the future is anticipated and number ofbuckets allocated accordingly, significant amount of space will bewasted initially.
If database shrinks, again space will be wasted. One option is periodic re-organization of the file with a new hash
function, but it is very expensive.
These problems can be avoided by using techniques that allowthe number of buckets to be modified dynamically.
-
7/27/2019 Index and Hashing manual and presentation foe students
66/96
Dynamic Hashing
-
7/27/2019 Index and Hashing manual and presentation foe students
67/96
Silberschatz, Korth and Sudarshan12. 67 Database System Concepts
Dynamic HashingGood for database that grows and shrinks in sizeAllows the hash function to be modified dynamicallyExtendable hashing one form of dynamic hashing
Hash function generates values over a large range typically b-bitintegers, with b = 32.At any time use only a prefix of the hash function to index into atable of bucket addresses.
Let the length of the prefix be i bits, 0 i 32.
Bucket address table size = 2 i. Initially i = 0Value of i grows and shrinks as the size of the database grows andshrinks.Multiple entries in the bucket address table may point to a bucket.
Thus, actual number of buckets is < 2 i The number of buckets also changes dynamically due tocoalescing and splitting of buckets.
General Extendable Hash Structure
-
7/27/2019 Index and Hashing manual and presentation foe students
68/96
Silberschatz, Korth and Sudarshan12. 68 Database System Concepts
General Extendable Hash Structure
I is called: Global depth; I j is called: Local depth
In this structure, i 2 = i 3 = i , whereas i 1 = i 1 (seenext slide for details)
-
7/27/2019 Index and Hashing manual and presentation foe students
69/96
Updates in Extendable Hash Structure
-
7/27/2019 Index and Hashing manual and presentation foe students
70/96
Silberschatz, Korth and Sudarshan12. 70 Database System Concepts
Updates in Extendable Hash Structure
If i > i j (more than one pointer to bucket j )
allocate a new bucket z , and set i j and i z to the old i j -+ 1. make the second half of the bucket address table entries pointing
to j to point to z
remove and reinsert each record in bucket j.
recompute new bucket for K j and insert record in the bucket (furthersplitting is required if the bucket is still full)
If i = i j (only one pointer to bucket j ) 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.
To split a bucket j when inserting record with search-key value K j :
Updates in Extendable Hash Structure(C )
-
7/27/2019 Index and Hashing manual and presentation foe students
71/96
Silberschatz, Korth and Sudarshan12. 71 Database System Concepts
(Cont.)
When inserting a value, if the bucket is full after several splits(that is, i reaches some limit b) create an overflow bucket insteadof splitting bucket entry table further.To delete a key value,
locate it in its bucket and remove it.The bucket itself can be removed if it becomes empty (withappropriate updates to the bucket address table).Coalescing of buckets can be done (can coalesce only with abuddy bucket having same value of i j and same i j 1 prefix, if it ispresent)Decreasing bucket address table size is also possible
Note: decreasing bucket address table size is an expensiveoperation and should be done only if number of buckets becomesmuch smaller than the size of the table
Example
2LOCAL DEPTHBucket A
-
7/27/2019 Index and Hashing manual and presentation foe students
72/96
Silberschatz, Korth and Sudarshan12. 72 Database System Concepts
Example
Directory is array of size 4.
To find bucket for r , take last ` global depth # bits of h (r ); we denote r byh (r ).
If h (r ) = 5 = binary 101, it is inbucket pointed to by 01.
Insert
: If bucket is full, split it (allocate new page, re-distribute). If necessary, double the directory. (As we will see, splitting abucket does not always require doubling; we can tell bycomparing global depth with local depth for the split bucket.)
13*00
01
10
11
2 2
2
2
GLOBAL DEPTH
DIRECTORY
Bucket A
Bucket B
Bucket C
Bucket D
DATA PAGES
10*
1* 21*
4* 12* 32* 16*
15* 7* 19*
5*
Insert h(r)=20 in previous slide
-
7/27/2019 Index and Hashing manual and presentation foe students
73/96
Silberschatz, Korth and Sudarshan12. 73 Database System Concepts
(Causes Doubling)
20*
00
01
10
11
2 2
2
2
LOCAL DEPTH 2
2
DIRECTORY
GLOBAL DEPTHBucket A
Bucket B
Bucket C
Bucket D
Bucket A2(`split image'of Bucket A)
1* 5* 21*13*
32*16*
10*
15* 7* 19*
4* 12*
19*
2
2
2
000
001
010
011
100
101
110
111
3
3
3DIRECTORY
Bucket A
Bucket B
Bucket C
Bucket D
Bucket A2(`split image'of Bucket A)
32*
1* 5* 21* 13*
16*
10*
15* 7*
4* 20*12*
LOCAL DEPTH
GLOBAL DEPTH
Use of Extendable Hash Structure:E l
-
7/27/2019 Index and Hashing manual and presentation foe students
74/96
Silberschatz, Korth and Sudarshan12. 74 Database System Concepts
Example
Initial Hash structure, bucket size = 2
-
7/27/2019 Index and Hashing manual and presentation foe students
75/96
Example (Cont )
-
7/27/2019 Index and Hashing manual and presentation foe students
76/96
Silberschatz, Korth and Sudarshan12. 76 Database System Concepts
Example (Cont.)Hash structure after insertion of Mianus record
Example (Cont )
-
7/27/2019 Index and Hashing manual and presentation foe students
77/96
Silberschatz, Korth and Sudarshan12. 77 Database System Concepts
Example (Cont.)
Hash structure after insertion of three Perryridge records
Using OVERFLOW BUCKET!
Example (Cont )
-
7/27/2019 Index and Hashing manual and presentation foe students
78/96
Silberschatz, Korth and Sudarshan12. 78 Database System Concepts
Example (Cont.)Hash structure after insertion of Redwood and Round Hillrecords
Performance of Extendable Hashing
-
7/27/2019 Index and Hashing manual and presentation foe students
79/96
Silberschatz, Korth and Sudarshan12. 79 Database System Concepts
Performance of Extendable Hashing
Assume a file with 10**7 records, record size is 200 bytes, key
size is 12 bytes, pointer size is 8 bytes.Assume Data block is 4K and blocks are in average half full
Assume Index blocks are also 4K and are in average half full
Therefore an Index block contain about 100 entries and a data
block contains about 10 records.With an Hash-index organization, the number of entries for thedirectory is: 10**7 / 100 = 10**5, therefore size of address is 17bits and size of directory 2**17 *4 = 512K. Access time is 2 (1 forIndex +1 for data file) ( or 2**17*8 = 1M )
With Hash file organization, the number of entries for thedirectory is 10**7/10 = 10**6, therefore size of address is 20 bitsand size of directory is 2**20*4 = 4M. Access time is only 1!
Extendable Hashing vs Other Schemes
-
7/27/2019 Index and Hashing manual and presentation foe students
80/96
Silberschatz, Korth and Sudarshan12. 80 Database System Concepts
Extendable Hashing vs. Other SchemesBenefits 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 thanmemory)
Need a tree structure to locate desired record in the structure!
Changing size of bucket address table is an expensive operation
Linear hashing is an alternative mechanism which avoids these
disadvantages at the possible cost of more bucket overflows
-
7/27/2019 Index and Hashing manual and presentation foe students
81/96
-
7/27/2019 Index and Hashing manual and presentation foe students
82/96
Silberschatz, Korth and Sudarshan12. 82 Database System Concepts
Linear Hashing (Contd.)
Directory avoided in LH by using overflow pages, and choosingbucket to split round-robin.
Splitting proceeds in `rounds . Round ends when all NR initial (for roundR) buckets are split. Buckets 0 to Next-1 have been split; Next to NR yetto be split.
Current round number is Level . Search: To find bucket for data entry r, find h Level (r ):
If h Level (r ) in range ` Next to NR , r belongs here.
Else, r could belong to bucket h Level (r ) or bucket h Level (r ) + NR;
must apply h Level +1(r ) to find out.
-
7/27/2019 Index and Hashing manual and presentation foe students
83/96
Silberschatz, Korth and Sudarshan12. 83 Database System Concepts
Overview of LH File
In the middle of a round.
Levelh
Buckets that existed at thebeginning of this round:
this is the range of
NextBucket to be split
of other buckets) in this round
Levelh search key value )(
search key value )(
Buckets split in this round:If is in this range, must use
h Level+1
`split image' bucket.to decide if entry is in
created (through splitting`split image' buckets:
Linear Hashing (Contd.)
-
7/27/2019 Index and Hashing manual and presentation foe students
84/96
Silberschatz, Korth and Sudarshan12. 84 Database System Concepts
Linear Hashing (Contd.)
Insert : Find bucket by applying hLevel
/ hLevel+1
: If bucket to insert into is full:
Add overflow page and insert data entry.(Maybe ) Split Next bucket and increment Next .
Can choose any criterion to `trigger split, usually but not necessarilywhen an overflow occurs. Since buckets are split round- robin, long overflow chains dont develop! Doubling of directory in Extendible Hashing is similar; switching of hashfunctions is implicit in how the # of bits examined is increased.
Example of Linear Hashing
-
7/27/2019 Index and Hashing manual and presentation foe students
85/96
Silberschatz, Korth and Sudarshan12. 85 Database System Concepts
p g
On split, h Level+1 is used to re-distribute entries.
0hh
1
( This inf o is for i llu stration only!)
Level=0, N=4
00
01
10
11
000
001
010
011
(Th e actual contents of th e li near hashed file)
Next=0
PRIMARYPAGES
Data entry r with h(r)=5
Primary bucket page
44* 36*32*
25*9* 5*
14* 18* 10* 30*
31* 35* 11*7*
0hh
1
Level=0
00
01
10
11
000
001
010
011
Next=1
PRIMARYPAGES
44* 36*
32*
25*9* 5*
14* 18* 10* 30*
31* 35* 11*7*
OVERFLOWPAGES
43*
00100
Example: End of a Round
-
7/27/2019 Index and Hashing manual and presentation foe students
86/96
Silberschatz, Korth and Sudarshan12. 86 Database System Concepts
p
0hh1
22*
00
01
10
11
000
001
010
011
00100
Next=3
01
10
101
110
Level=0PRIMARYPAGES
OVERFLOWPAGES
32*
9*
5*
14*
25*
66* 10*18* 34*
35*31* 7* 11* 43*
44*36*
37* 29*
30*
0hh 1
37*
00
01
10
11
000
001
010
011
00100
10
101
110
Next=0
Level=1
111
11
PRIMARYPAGES
OVERFLOWPAGES
11
32*
9* 25*
66* 18* 10* 34*
35* 11*
44* 36*
5* 29*
43*
14* 30* 22*
31* 7*
50* page = 2K
Comparison of Ordered Indexing and Hashing
-
7/27/2019 Index and Hashing manual and presentation foe students
87/96
Silberschatz, Korth and Sudarshan12. 87 Database System Concepts
Cost of periodic re-organization
Relative frequency of insertions and deletionsIs it desirable to optimize average access time at the expense ofworst-case access time?
Expected type of queries:Hashing is generally better at retrieving records having a specifiedvalue of the key.If range queries are common, ordered indices are to be preferred
Index Definition in SQL
-
7/27/2019 Index and Hashing manual and presentation foe students
88/96
Silberschatz, Korth and Sudarshan12. 88 Database System Concepts
QCreate an index
create index on )
E.g.: create index b-index on branch(branch-name)
Use create unique index to indirectly specify and enforce thecondition that the search key is a candidate key is a candidate
key.Not really required if SQL unique integrity constraint is supported
To drop an indexdrop index
Multiple-Key Access
-
7/27/2019 Index and Hashing manual and presentation foe students
89/96
Silberschatz, Korth and Sudarshan12. 89 Database System Concepts
p yUse multiple indices for certain types of queries.Example:
select account-number
from account where branch-name = Perryridge and balance - 1000
Possible strategies for processing query using indices on singleattributes:
1. Use index on branch-name to find accounts with balances of $1000; testbranch- name = Perryridge .
2. Use index on balance to find accounts with balances of $1000; test branch-name = Perryridge .
3. Use branch-name index to find pointers to all records pertaining to thePerryridge branch. Similarly use index on balance . Take intersection ofboth sets of pointers obtained.
Indices on Multiple Attributes
-
7/27/2019 Index and Hashing manual and presentation foe students
90/96
Silberschatz, Korth and Sudarshan12. 90 Database System Concepts
p
With the where clausewhere branch-name = Perryridge and balance = 1000the index on the combined search-key will fetch only recordsthat satisfy both conditions.Using separate indices in less efficient we may fetch many
records (or pointers) that satisfy only one of the conditions.Can also efficiently handlewhere branch-name - Perryridge and balance < 1000
But cannot efficiently handlewhere branch-name < Perryridge and balance = 1000
May fetch many records that satisfy the first but not thesecond condition.
Suppose we have an index on combined search-key(branch-name, balance ).
Indices on Multiple Attributes
-
7/27/2019 Index and Hashing manual and presentation foe students
91/96
Silberschatz, Korth and Sudarshan12. 91 Database System Concepts
p
Example: find all objects within the following boundaries:
0
-
7/27/2019 Index and Hashing manual and presentation foe students
92/96
Silberschatz, Korth and Sudarshan12. 92 Database System Concepts
y
A classic problem in computer science!
Data requested in sorted ordere.g., find students in increasing gpa order
Sorting is first step in bulk loading B+ tree index.
Sorting useful for eliminating duplicate copies in a collection of records(Why?)
Sort-merge join algorithm involves sorting.
Problem: sort 1Gb of data with 1Mb of RAM.why not virtual memory?
2-Way Sort: Requires 3 Buffers
-
7/27/2019 Index and Hashing manual and presentation foe students
93/96
Silberschatz, Korth and Sudarshan12. 93 Database System Concepts
y q
Pass 1: Read a page, sort it, write it.only one buffer page is used
Pass 2, 3 , , etc.: three buffer pages used.
Main memory buffers
INPUT 1
INPUT 2OUTPUT
DiskDisk
Two-Way External Merge Sort
-
7/27/2019 Index and Hashing manual and presentation foe students
94/96
Silberschatz, Korth and Sudarshan12. 94 Database System Concepts
y g
Each pass we read + write eachpage in file.
N pages in the file => the number ofpasses
So toal cost is:
Idea: Div ide and conq uer : sortsubfiles and merge
log 2 1 N
2 12 N N log
Input file
1-page runs
2-page runs
4-page runs
8-page runs
PASS 0
PASS 1
PASS 2
PASS 3
9
3,4 6,2 9,4 8,7 5,6 3,1 2
3,4 5,62,6 4,9 7,8 1,3 2
2,34,6
4,78,9
1,35,6 2
2,34,46,78,9
1,23,56
1,22,33,44,56,67,8
General External Merge Sort
-
7/27/2019 Index and Hashing manual and presentation foe students
95/96
Silberschatz, Korth and Sudarshan12. 95 Database System Concepts
To sort a file with N pages using B buffer pages:Pass 0: use B buffer pages. Produce sorted runs of B pages each.
Pass 2 , , etc.: merge B-1 runs. N B/
B Main memory buffers
INPUT 1
INPUT B-1
OUTPUT
DiskDisk
INPUT 2
. . . . . .. . .
More than 3 buffer pages. How can we utilize them?
Cost of External Merge Sort
-
7/27/2019 Index and Hashing manual and presentation foe students
96/96
Number of passes:
Cost = 2N * (# of passes)E.g., with 5 buffer pages, to sort 108 page file:
Pass 0: = 22 sorted runs of 5 pages each (last run is only3 pages)
Pass 1: = 6 sorted runs of 20 pages each (last run is only
8 pages)Pass 2: 2 sorted runs, 80 pages and 28 pages
Pass 3: Sorted file of 108 pages
For example: 0 passes (main memory) = 1N (writing output notconsidered)
1 pass = 3N
1 1log / B N B
108 5/
22 4/