Você está na página 1de 122

Chapter 12: Indexing and Hashing

Rev. Sep 17, 2008

Database System Concepts, 5th Ed.


Silberschatz, Korth and Sudarshan See www.db-book.com for conditions on re-use

Chapter 12: Indexing and Hashing


n Basic Concepts n Ordered Indices n B+-Tree Index Files n B-Tree Index Files n Static Hashing n Dynamic Hashing

n Comparison of Ordered Indexing and Hashing


n Index Definition in SQL n Multiple-Key Access

Database System Concepts - 5th Edition.

12.2

Silberschatz, Korth and Sudarshan

Basic Concepts
n Indexing mechanisms used to speed up access to desired data.

E.g., author catalog in library l Textbook n Search Key - attribute to set of attributes used to look up records in a file. n An index file consists of records (called index entries) of the form pointer search-key
l

n Index files are typically much smaller than the original file

further reducing the effort needed to find particular result. n Two basic kinds of indices: l Ordered indices: search keys are stored in sorted order l Hash indices: search keys are distributed uniformly across buckets using a hash function.

Database System Concepts - 5th Edition.

12.3

Silberschatz, Korth and Sudarshan

Index on Sequential File


An index is another file containing key-pointer pairs of the form (K,a) n K is a search key n a is an address (pointer)
n

The record at address a has search key K n Particularly useful when the search key is the primary key of the relation
n
n

Possible Data structure l Simple index on sorted file l Secondary index on unsorted file l B tree l Hash table

Database System Concepts - 5th Edition.

12.4

Silberschatz, Korth and Sudarshan

Index Evaluation Metrics


n Access types supported efficiently. E.g.,

n n

records with a specified value in the attribute l or records with an attribute value falling in a specified range of values (e.g. 10000 < salary < 40000) Access time l The time it takes to find a particular data item, or set of data item. Insertion time l Time it takes to insert a new data item.This value includes the time it takes to find the correct place to insert the new data item, as well as the time it take to update the index structure Deletion time Space overhead
l

Database System Concepts - 5th Edition.

12.5

Silberschatz, Korth and Sudarshan

Ordered Indices
n In an ordered index, index entries are stored sorted on the

search key value. E.g., author catalog in library, index of book.


n Primary index: in a sequentially ordered file, the index whose

search key specifies the sequential order of the file.


l
l

Also called clustering index


The search key of a primary index is usually but not necessarily the primary key.

n Secondary index: an index whose search key specifies an order

different from the sequential order of the file. Also called non-clustering index.
n Index-sequential file: ordered sequential file with a primary index.

Database System Concepts - 5th Edition.

12.6

Silberschatz, Korth and Sudarshan

Dense Index Files


n

Dense index Index record appears for every search-key value in the file. In a dense primary index, the index record contains the searchkey value and a pointer to first data record with that search-key value.

Database System Concepts - 5th Edition.

12.7

Silberschatz, Korth and Sudarshan

Sparse Index Files


n Sparse Index: contains index records for only some search-key values.
l l

Applicable when records are sequentially ordered on search-key As is true in dense indices each index record contains a search-key value and a pointer to first data record with the search-key value. Find index record with largest search-key value < K We start at the record pointed to by that index entry, follow the pointers in the file until we find the desired record.

n To locate a record with search-key value K we:


l l

Database System Concepts - 5th Edition.

12.8

Silberschatz, Korth and Sudarshan

Sparse Index example


n
n

If we want to find the records for Perryridge branch.


Since there is no index entry for Perryridge the last entry before Perryridge is Mianus we follow that pointer. Then read the file in sequential order until we find the first Perryridge record, and begin processing at that point.

Database System Concepts - 5th Edition.

12.9

Silberschatz, Korth and Sudarshan

Sparse Index Files (Cont.)


n Compared to dense indices:
l

Less space and less maintenance overhead for insertions and deletions.

Generally slower than dense index for locating records.

n Good tradeoff: sparse index with an index entry for every block in

file, corresponding to least search-key value in the block.

Database System Concepts - 5th Edition.

12.10

Silberschatz, Korth and Sudarshan

Example
n

Let assume file(database) have 100,000 records with 100 record per block.
l

Assign one index entry per block

By applying binary search it requires as many as [ log2 (b)] where b is no of block.


For our 100-block index, binary search requires seven block reads. Assume per block on disk it takes 30 milliseconds, search will take 210 milliseconds, which is long.

Database System Concepts - 5th Edition.

12.11

Silberschatz, Korth and Sudarshan

Multilevel Index
n If primary index does not fit in memory, access becomes

expensive.
n Solution: treat primary index kept on disk as a sequential file

and construct a sparse index on it.


l l

outer index a sparse index of primary index inner index the primary index file

n If even outer index is too large to fit in main memory, yet

another level of index can be created, and so on.


n Searching for records with a multilevel index requires

significantly fewer I/O operations


n Indices at all levels must be updated on insertion or deletion

from the file.

Database System Concepts - 5th Edition.

12.12

Silberschatz, Korth and Sudarshan

Multilevel Index (Cont.)

Database System Concepts - 5th Edition.

12.13

Silberschatz, Korth and Sudarshan

Two-Level Index Example


Sparse 2nd level
10 90 170 250 330 410 490 570 10 30 50 70

Sequential File

10 20
30 40 50 60 70 80 90 100

90 110 130 150 170 190 210 230

Database System Concepts - 5th Edition.

12.14

Silberschatz, Korth and Sudarshan

Index Update: Record Deletion


If deleted record was the only record in the file with its particular searchkey value, the search-key is deleted from the index also. n Single-level index deletion: l Dense indices deletion of search-key: similar to file record deletion. l Sparse indices 1. If the index does not contain an index record with the search-key value of the deleted record, nothing needs to be done to index. 2. Otherwise the system takes the following actions: If the deleted record was the only record with its search key the system replaces the corresponding index record with an index record for the next search-key value. If the next searchkey value already has an index entry, the entry is deleted instead of replaced. Otherwise, if the index record for the search-key value points to the record being deleted, the system updates the index record to point to the next record with the same search-key value.
n

Database System Concepts - 5th Edition.

12.15

Silberschatz, Korth and Sudarshan

Deletion from dense index

delete record 30
10 20 40 30 40
50 60 70 80

10 20 30 40 40 50 60

70 80

Database System Concepts - 5th Edition.

12.16

Silberschatz, Korth and Sudarshan

Deletion from sparse index

10 30 50 70
90 110 130 150

10 20 30 40 50 60

70 80

Database System Concepts - 5th Edition.

12.17

Silberschatz, Korth and Sudarshan

Deletion from sparse index

delete record 40
10 30 50 70
90 110 130 150

10 20 30 40 50 60

70 80

Database System Concepts - 5th Edition.

12.18

Silberschatz, Korth and Sudarshan

Deletion from sparse index

delete record 30
10 40 30 50 70
90 110 130 150

10 20 30 40 40 50 60

70 80

Database System Concepts - 5th Edition.

12.19

Silberschatz, Korth and Sudarshan

Deletion from sparse index

delete records 30 & 40


10 50 30 70 50 70
90 110 130 150

10 20 30 40 50 60

70 80

Database System Concepts - 5th Edition.

12.20

Silberschatz, Korth and Sudarshan

Index Update: Record Insertion


n Single-level index insertion:
l l

Perform a lookup using the key value from inserted record 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.

n Multilevel insertion (as well as deletion) algorithms are simple

extensions of the single-level algorithms

Database System Concepts - 5th Edition.

12.21

Silberschatz, Korth and Sudarshan

Insertion into sparse index

10 30 40 60

10 20 30 40 50

60

Database System Concepts - 5th Edition.

12.22

Silberschatz, Korth and Sudarshan

Insertion into sparse index

insert record 34
10 30 40 60

10 20 30 34 40 50

our lucky day! we have free space where we need it!

60

Database System Concepts - 5th Edition.

12.23

Silberschatz, Korth and Sudarshan

Insertion into sparse index

insert record 15
10 20 30 40 60

10 20 15 30 20 30 40 50

Illustrated: Immediate reorganization 60 Variation:


insert new block (chained file) update index

Database System Concepts - 5th Edition.

12.24

Silberschatz, Korth and Sudarshan

Types of Single-Level Indexes


n

Secondary Index l

A secondary index provides a secondary means of accessing a file for which some primary access already exists.

The secondary index may be on a field which is a candidate key and has a unique value in every record, or a nonkey with duplicate values.
The index is an ordered file with two fields. The first field is of the same data type as some nonordering field of the data file that is an indexing field. The second field is either a block pointer or a record pointer. There can be many secondary indexes (and hence, indexing fields) for the same file.

Includes one entry for each record in the data file; hence, it is a dense index
12.25 Silberschatz, Korth and Sudarshan

Database System Concepts - 5th Edition.

FIGURE 14.4 A dense secondary index (with block pointers) on a nonordering key field of a file.

Database System Concepts - 5th Edition.

12.26

Silberschatz, Korth and Sudarshan

Secondary Indices Example

Secondary index on balance field of account n Index record points to a bucket that contains pointers to all the

actual records with that particular search-key value.


n Secondary indices have to be dense
Database System Concepts - 5th Edition. 12.27 Silberschatz, Korth and Sudarshan

Primary and Secondary Indices


n Indices offer substantial benefits when searching for records. n BUT: Updating indices imposes overhead on database

modification --when a file is modified, every index on the file must be updated,
n Sequential scan using primary index is efficient, but a

sequential scan using a secondary index is expensive


l

Each record access may fetch a new block from disk

Block fetch requires about 5 to 10 micro seconds, versus about 100 nanoseconds for memory access

Database System Concepts - 5th Edition.

12.28

Silberschatz, Korth and Sudarshan

B+-Tree Index Files


B+-tree indices are an alternative to indexed-sequential files.
n Disadvantage of indexed-sequential files

performance degrades as file grows, since many overflow blocks get created. l Periodic reorganization of entire file is required. n Advantage of B+-tree index files: l automatically reorganizes itself with small, local, changes, in the face of insertions and deletions. l Reorganization of entire file is not required to maintain performance. n (Minor) disadvantage of B+-trees: l extra insertion and deletion overhead, space overhead. n Advantages of B+-trees outweigh disadvantages l B+-trees are used extensively
l
Database System Concepts - 5th Edition. 12.29 Silberschatz, Korth and Sudarshan

Three Types B-Tree Nodes

n Root node - contains node pointers to branch nodes. n Branch node - contains pointers to leaf nodes n Leaf node - contains index items and horizontal

pointers to other leaf nodes.

Database System Concepts - 5th Edition.

12.30

Silberschatz, Korth and Sudarshan

A node in a search tree with pointers to subtrees below it.

Database System Concepts - 5th Edition.

12.31

Silberschatz, Korth and Sudarshan

B+-Tree Index Files (Cont.)


A B+-tree is a rooted tree satisfying the following properties:
n n n n

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 and n children. A leaf node has between (n1)/2 and n1 values Special cases:
l l

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 the tree), it can have between 0 and (n1) values.

n n

Minimum no of keys in leaf node (n/2) Minimum no of keys in non-leaf node is (n+1)/2 - 1

Database System Concepts - 5th Edition.

12.32

Silberschatz, Korth and Sudarshan

B+-Tree Node Structure


n

Typical node

l l

Ki are the search-key values Pi are pointers to children (for non-leaf nodes) or pointers to records or buckets of records (for leaf nodes). K1 < K2 < K3 < . . . < Kn1

n The search-keys in a node are ordered

Database System Concepts - 5th Edition.

12.33

Silberschatz, Korth and Sudarshan

Example of a B+-tree

B+-tree for account file (n = 3)

Database System Concepts - 5th Edition.

12.34

Silberschatz, Korth and Sudarshan

Example of B+-tree

B+-tree for account file (n = 5)


n Leaf nodes must have between 2 and 4 values

((n1)/2 and n 1, with n = 5).


n Non-leaf nodes other than root must have between 3

and 5 children ((n/2 and n with n =5).


n Root must have at least 2 children.

Database System Concepts - 5th Edition.

12.35

Silberschatz, Korth and Sudarshan

B+Tree Example
Root

n=3

100

120 150 180 100 101 110 120 130


12.36

30

Database System Concepts - 5th Edition.

150 156 179

Silberschatz, Korth and Sudarshan

180 200

3 5 11

30 35

Sample non-leaf

120

150

to keys < 120

to keys

to keys

to keys

180

120 k<150

150k<180 180

Database System Concepts - 5th Edition.

12.37

Silberschatz, Korth and Sudarshan

Sample leaf node:


From non-leaf node to next leaf

To record with key 120

Database System Concepts - 5th Edition.

To record with key 130

12.38

unused

in sequence

120

130

Silberschatz, Korth and Sudarshan

Observations about B+-trees


n Since the inter-node connections are done by pointers,

logically close blocks need not be physically close.


n The non-leaf levels of the B+-tree form a hierarchy of sparse

indices.
n The B+-tree contains a relatively small number of levels
Level Next ..

below root has at least 2* n/2 values

level has at least 2* n/2 * n/2 values

etc.

If there are K search-key values in the file, the tree height is no more than logn/2(K) thus searches can be conducted efficiently.

n Insertions and deletions to the main file can be handled

efficiently, as the index can be restructured in logarithmic time (as we shall see).
Database System Concepts - 5th Edition. 12.39 Silberschatz, Korth and Sudarshan

Queries on B+-Trees
n

Find all records with a search-key value of k.


1. 2.

N=root Repeat
1. 2. 3.

Examine N for the smallest search-key value > k. If such a value exists, assume it is Ki. Then set N = Pi Otherwise k Kn1. Set N = Pn

Until N is a leaf node


3. 4.

If for some i, key Ki = k follow pointer Pi to the desired record or bucket. Else no record with search-key value k exists.

Database System Concepts - 5th Edition.

12.40

Silberschatz, Korth and Sudarshan

Queries on B+-Trees (Cont.)


n If there are K search-key values in the file, the height of the

tree is no more than logn/2(K). kilobytes


l

n A node is generally the same size as a disk block, typically 4

and n is typically around 100 (40 bytes per index entry). at most log50(1,000,000) = 4 nodes are accessed in a lookup.

n With 1 million search key values and n = 100


l

n Contrast this with a balanced binary tree with 1 million search

key values around 20 nodes are accessed in a lookup


l

above difference is significant since every node access may need a disk I/O, costing around 20 milliseconds

Database System Concepts - 5th Edition.

12.41

Silberschatz, Korth and Sudarshan

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 add the record to the main file (and create a bucket if necessary) If there is room in the leaf node, insert (key-value, pointer) pair in the leaf node Otherwise, split the node (along with the new (key-value, pointer) entry) as discussed in the next slide.

3. If the search-key value is not present, then


1.

2.

3.

Database System Concepts - 5th Edition.

12.42

Silberschatz, Korth and Sudarshan

Updates on B+-Trees: Insertion (Cont.)


n

Splitting a leaf node:


l

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. In the worst case the root node may be split increasing the height of the tree by 1.

Splitting of nodes proceeds upwards till a node that is not full is found.
l

Result of splitting node containing Brighton and Downtown on inserting Clearview Next step: insert entry with (Downtown,pointer-to-new-node) into parent
Database System Concepts - 5th Edition. 12.43 Silberschatz, Korth and Sudarshan

Updates on B+-Trees: Insertion (Cont.)

B+-Tree before and after insertion of Clearview


Database System Concepts - 5th Edition. 12.44 Silberschatz, Korth and Sudarshan

Insertion in B+-Trees (Cont.)


n Splitting a non-leaf node: when inserting (k,p) into an already

full internal node N


l

Copy N to an in-memory area M with space for n+1 pointers and n keys Insert (k,p) into M Copy P1,K1, , K n/2-1,P n/2 from M back into node N Copy Pn/2+1,K n/2+1,,Kn,Pn+1 from M into newly allocated node N Insert (K n/2,N) into parent N
Mianus

l l l

Read pseudocode in book!

Downtown Mianus Perryridge

Downtown

Redwood

Database System Concepts - 5th Edition.

12.45

Silberschatz, Korth and Sudarshan

Inserting a Data Entry into a B+ Tree


1) Find

correct leaf node 2) Add index entry to the node 3) If enough space, done! 4) Else, split the node Redistribute entries evenly between the current node and the new node 5) Insert <middle key, ptr to new node> to the parent 6) Go to Step 3

Database System Concepts - 5th Edition.

12.46

Silberschatz, Korth and Sudarshan

Insert into B+tree

First lookup the proper leaf; (a) simple case


l

leaf not full: just insert (key, pointer-to-record)

(b) leaf overflow (c) non-leaf overflow (d) new root

Database System Concepts - 5th Edition.

12.47

Silberschatz, Korth and Sudarshan

(a) Insert key = 32

n=3
100

3 5 11

30
Database System Concepts - 5th Edition.

30 31 32
12.48

Silberschatz, Korth and Sudarshan

(b) Insert key = 7

n=3
100 3 57 11 30
12.49

7
Database System Concepts - 5th Edition.

30 31

3 5

Silberschatz, Korth and Sudarshan

(c) Insert key = 160

n=3

100

160
120 150 180

180
12.50

Database System Concepts - 5th Edition.

160 179

150 156 179

Silberschatz, Korth and Sudarshan

180 200

(d) New root, insert 45

n=3
Height grows at root => balance maintained

10 20 30

30

new root

30 32 40

10 12

20 25

40

Database System Concepts - 5th Edition.

12.51

Silberschatz, Korth and Sudarshan

40 45

1 2 3

Updates on B+-Trees: Deletion


n Find the record to be deleted, and remove it from the main file

and from the bucket (if present)


n Remove (search-key value, pointer) from the leaf node if there

is no bucket or if the bucket has become empty


n If the node has too few entries due to the removal, and the

entries in the node and a sibling fit into a single node, then merge siblings:
l

Insert all the search-key values in the two nodes into a single node (the one on the left), and delete the other node.
Delete the pair (Ki1, Pi), where Pi is the pointer to the deleted node, from its parent, recursively using the above procedure.

Database System Concepts - 5th Edition.

12.52

Silberschatz, Korth and Sudarshan

Updates on B+-Trees: Deletion


n Otherwise, if the node has too few entries due to the removal,

but the entries in the node and a sibling do not fit into a single node, then redistribute pointers:
l

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.

n The node deletions may cascade upwards till a node which has

n/2 or more pointers is found.

n If the root node has only one pointer after deletion, it is deleted

and the sole child becomes the root.

Database System Concepts - 5th Edition.

12.53

Silberschatz, Korth and Sudarshan

Examples of B+-Tree Deletion

Before and after deleting Downtown n Deleting Downtown causes merging of under-full leaves
l

leaf node can become empty only for n=3!


12.54 Silberschatz, Korth and Sudarshan

Database System Concepts - 5th Edition.

Examples of B+-Tree Deletion (Cont.)

Before and After deletion of Perryridge from result of previous example


Database System Concepts - 5th Edition. 12.55 Silberschatz, Korth and Sudarshan

Examples of B+-Tree Deletion (Cont.)

n Leaf with Perryridge becomes underfull (actually empty, in this

special case) and merged with its sibling. n As a result Perryridge nodes parent became underfull, and was merged with its sibling l Value separating two nodes (at parent) moves into merged node l Entry deleted from parent n Root node then has only one child, and is deleted

Database System Concepts - 5th Edition.

12.56

Silberschatz, Korth and Sudarshan

Example of B+-tree Deletion (Cont.)

Before and after deletion of Perryridge from earlier example


n n

Parent of leaf containing Perryridge became underfull, and borrowed a pointer from its left sibling Search-key value in the parents parent changes as a result
12.57 Silberschatz, Korth and Sudarshan

Database System Concepts - 5th Edition.

Deleting a Data Entry from a B+ Tree


1) Find correct leaf node 2) Remove the entry from the node 3) If the node is at least half full, done! 4) Else, possibly borrow some entries from a sibling 5) If not possible, merge the node with the sibling 6) Delete the separator between the node and the sibling from the parent node 7) Go to Step 3

Database System Concepts - 5th Edition.

12.58

Silberschatz, Korth and Sudarshan

Deletion from B+tree

Again, first lookup the proper leaf;


(a): Simple case: no underflow; Otherwise ... (b): Borrow keys from an adjacent sibling (if it doesn't become too empty); Else ... (c): Coalesce with a sibling node -> (d): Cases (a), (b) or (c) at non-leaf

Database System Concepts - 5th Edition.

12.59

Silberschatz, Korth and Sudarshan

(b) Borrow keys


l

Delete 50

n=4

=> min # of keys in a leaf = 5/2 = 2

Database System Concepts - 5th Edition.

12.60

35 40 50

10 20 30 35

10 40 35 100

Silberschatz, Korth and Sudarshan

(c) Coalesce with a sibling


l

Delete 50

n=4

20 30 40

20 40 100
Database System Concepts - 5th Edition. 12.61

40 50

Silberschatz, Korth and Sudarshan

(d) Non-leaf coalesce


l

Delete 37

n=4

=> min # of keys in a non-leaf = (n+1)/2 - 1=3-1= 2

new root
10 20 25 40
30 40 25 26 30 30 37

10 14

20 22

25

Database System Concepts - 5th Edition.

12.62

Silberschatz, Korth and Sudarshan

40 45

1 3

B+ Trees: Summary
n

Searching:
l

logd(n) Where d is the order, and n is the number of entries Find the leaf to insert into If full, split the node, and adjust index accordingly Similar cost as searching Find the leaf node Delete May not remain half-full; must adjust the index accordingly

Insertion:
l l l

Deletion
l l l

Database System Concepts - 5th Edition.

12.63

Silberschatz, Korth and Sudarshan

Insert 23*
Root
13 17 24 30

2*

3*

5*

7*

14* 16*

19* 20* 22*

24* 27* 29*

33* 34* 38* 39*

No splitting required.
Root
13 17 24

30

2*

3*

5*

7*

14* 16*

19* 20* 22* 23*


12.64

24* 27* 29*

33* 34* 38* 39*


Silberschatz, Korth and Sudarshan

Database System Concepts - 5th Edition.

Example B+ Tree - Inserting 8*

Root Root
13 17 17 24 30

13

24

30

2* 2*

3* 3*

5*

7*

5*

14* 16* 7* 8*

14* 16*

24* 27* 29* 19* 20* 22* 19* 20* 22* 24* 27* 29*

33* 34* 38* 39* 33* 34* 38* 39*

v Notice that root was split, leading to increase in height. v In this example, we can avoid split by re-distributing entries; however, this is usually not done in practice.
Database System Concepts - 5th Edition. 12.66 Silberschatz, Korth and Sudarshan

Delete 19*
Root
17

Root
5 13 13 2* 3* 5* 7* 8* 17 24 30 33* 34* 38* 39* 24 30

14* 16*

19* 20* 22*

24* 27* 29*

2*

3*

5*

7*

14* 16*

19* 20* 22*

24* 27* 29*

33* 34* 38* 39*

Root
17

13

24

30

2*

3*

5*

7* 8*

14* 16*

20* 22*
12.67

24* 27* 29*

33* 34* 38* 39*

Database System Concepts - 5th Edition.

Silberschatz, Korth and Sudarshan

Delete 20* ...


Root
17

13

24

30

2*

3*

5*

7* 8*

14* 16*

20* 22*

24* 27* 29*

33* 34* 38* 39*

Root
17

13

27

30

2*

3*

5*

7* 8*

14* 16*

22* 24*
12.68

27* 29*

33* 34* 38* 39*


Silberschatz, Korth and Sudarshan

Database System Concepts - 5th Edition.

Delete 19* and 20* ...


n n n

Deleting 19* is easy. Deleting 20* is done with re-distribution. Notice how middle key is copied up. Further deleting 24* results in more drastic changes

Database System Concepts - 5th Edition.

12.69

Silberschatz, Korth and Sudarshan

Delete 24* ...


Root
17

13

27

30

2*

3*

5*

7* 8*

14* 16*

22* 24*

27* 29*

33* 34* 38* 39*

Root
17

No redistribution from neighbors possible

13

27

30

2*

3*

5*

7* 8*

14* 16*

22*
12.70

27* 29*

33* 34* 38* 39*


Silberschatz, Korth and Sudarshan

Database System Concepts - 5th Edition.

Deleting 24*

n n

Must merge. Observe `toss of index entry (on right), and `pull down of index entry (below).

30

22*

27*

29*

33*

34*

38*

39*

Root
5 13

17

30

2*

3*

5*

7*

8*

14* 16*

22* 27* 29*

33* 34* 38* 39*

Database System Concepts - 5th Edition.

12.71

Silberschatz, Korth and Sudarshan

Example of Non-leaf Re-distribution

Tree is shown below during deletion of 24*. (What could be a possible initial tree?)

In contrast to previous example, can re-distribute entry from left child of root to right child.

Root
22

13

17

20

30

2* 3*

5* 7* 8*

14* 16*

17* 18*

20* 21*

22* 27* 29*

33* 34* 38* 39*

Database System Concepts - 5th Edition.

12.72

Silberschatz, Korth and Sudarshan

After Re-distribution

n n

Intuitively, entries are re-distributed by `pushing through the splitting entry in the parent node. It suffices to re-distribute index entry with key 20; weve re-distributed 17 as well for illustration.

Root
17

13

20

22

30

2* 3*

5* 7* 8*

14* 16*

17* 18*
12.73

20* 21*

22* 27* 29*

33* 34* 38* 39*

Database System Concepts - 5th Edition.

Silberschatz, Korth and Sudarshan

B+-Tree File Organization


n Index file degradation problem is solved by using B+-Tree indices. n Data file degradation problem is solved by using B+-Tree File

Organization.
n The leaf nodes in a B+-tree file organization store records, instead

of pointers.
n Leaf nodes are still required to be half full
l

Since records are larger than pointers, the maximum number of records that can be stored in a leaf node is less than the number of pointers in a nonleaf node.

n Insertion and deletion are handled in the same way as insertion

and deletion of entries in a B+-tree index.

Database System Concepts - 5th Edition.

12.74

Silberschatz, Korth and Sudarshan

B+-Tree File Organization (Cont.)

Example of B+-tree File Organization


n Good space utilization important since records use more space than

pointers.
n To improve space utilization, involve more sibling nodes in

redistribution during splits and merges


l

Involving 2 siblings in redistribution (to avoid split / merge where possible) results in each node having at least 2n / 3 entries
12.75 Silberschatz, Korth and Sudarshan

Database System Concepts - 5th Edition.

Indexing Strings
n Variable length strings as keys
l l

Variable fanout Use space utilization as criterion for splitting, not number of pointers Key values at internal nodes can be prefixes of full key
Keep

n Prefix compression
l

enough characters to distinguish entries in the subtrees separated by the key value E.g. Silas and Silberschatz can be separated by Silb

Keys in leaf node can be compressed by sharing common prefixes

Database System Concepts - 5th Edition.

12.76

Silberschatz, Korth and Sudarshan

B-Tree Index Files


n Similar to B+-tree, but B-tree allows search-key values

to appear only once; eliminates redundant storage of search keys.


n Search keys in nonleaf nodes appear nowhere else in

the B-tree; an additional pointer field for each search key in a nonleaf node must be included.
n Generalized B-tree leaf node

n Nonleaf node pointers Bi are the bucket or file record

pointers.
Database System Concepts - 5th Edition. 12.77 Silberschatz, Korth and Sudarshan

B-Tree Index File Example

B-tree (above) and B+-tree (below) on same data

Database System Concepts - 5th Edition.

12.78

Silberschatz, Korth and Sudarshan

B-Tree Index Files (Cont.)


n Advantages of B-Tree indices:
l l

May use less tree nodes than a corresponding B+-Tree. Sometimes possible to find search-key value before reaching leaf node. Only small fraction of all search-key values are found early Non-leaf nodes are larger, so fan-out is reduced. Thus, BTrees typically have greater depth than corresponding B+-Tree Insertion and deletion more complicated than in B+-Trees Implementation is harder than B+-Trees.

n Disadvantages of B-Tree indices:


l l

l l

n Typically, advantages of B-Trees do not out weigh disadvantages.

Database System Concepts - 5th Edition.

12.79

Silberschatz, Korth and Sudarshan

Multiple-Key Access
n Use multiple indices for certain types of queries. n Example:

select account_number from account where branch_name = Perryridge and balance = 1000 n Possible strategies for processing query using indices on single attributes: 1. Use index on branch_name to find accounts with branch name Perryridge; test balance = 1000 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 the Perryridge branch. Similarly use index on balance. Take intersection of both sets of pointers obtained.

Database System Concepts - 5th Edition.

12.80

Silberschatz, Korth and Sudarshan

Indices on Multiple Keys


n Composite search keys are search keys containing more

than one attribute


l

E.g. (branch_name, balance) a1 < b1, or a1=b1 and a2 < b2

n Lexicographic ordering: (a1, a2) < (b1, b2) if either


l l

Database System Concepts - 5th Edition.

12.81

Silberschatz, Korth and Sudarshan

Indices on Multiple Attributes


Suppose we have an index on combined search-key (branch_name, balance).
n

For

where branch_name = Perryridge and balance = 1000 the index on (branch_name, balance) can be used to fetch only records that satisfy both conditions.
l

Using separate indices in less efficient we may fetch many records (or pointers) that satisfy only one of the conditions. where branch_name = Perryridge and balance < 1000

n Can also efficiently handle n But cannot efficiently handle

where branch_name < Perryridge and balance = 1000


l

May fetch many records that satisfy the first but not the second condition
12.82 Silberschatz, Korth and Sudarshan

Database System Concepts - 5th Edition.

Non-Unique Search Keys


n Alternatives:
l l

Buckets on separate block (bad idea) List of tuple pointers with each key
Low

space overhead, no extra cost for queries code to handle read/update of long lists

Extra

Deletion

of a tuple can be expensive if there are many duplicates on search key (why?) storage overhead for keys code for insertion/deletion

Make search key unique by adding a record-identifier


Extra Simpler

Widely

used

Database System Concepts - 5th Edition.

12.83

Silberschatz, Korth and Sudarshan

Other Issues in Indexing


n Covering indices

Add extra attributes to index so (some) queries can avoid fetching the actual records Particularly useful for secondary indices Why? l Can store extra attributes only at leaf n Record relocation and secondary indices l If a record moves, all secondary indices that store record pointers have to be updated l Node splits in B+-tree file organizations become very expensive l Solution: use primary-index search key instead of record pointer in secondary index Extra traversal of primary index to locate record Higher cost for queries, but node splits are cheap Add record-id if primary-index search key is non-unique
l
Database System Concepts - 5th Edition. 12.84 Silberschatz, Korth and Sudarshan

Hashing

Database System Concepts, 5th Ed.


Silberschatz, Korth and Sudarshan See www.db-book.com for conditions on re-use

Static Hashing
n n n n n

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 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 access, insertion as well as deletion. Records with different search-key values may be mapped to the same bucket; thus entire bucket has to be searched sequentially to locate a record.

Database System Concepts - 5th Edition.

12.86

Silberschatz, Korth and Sudarshan

Example of Hash File Organization


Hash file organization of account file, using branch_name as key (See figure in next slide.)
n

There are 10 buckets,

n
n

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 10
l

E.g. h(Perryridge) = 5

h(Round Hill) = 3 h(Brighton) = 3

Database System Concepts - 5th Edition.

12.87

Silberschatz, Korth and Sudarshan

Example of Hash File Organization


Hash file organization of account file, using branch_name as key (see previous slide for details).

Database System Concepts - 5th Edition.

12.88

Silberschatz, Korth and Sudarshan

Hash Functions
n

Worst hash function maps all search-key values to the same bucket; 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 assigned the same 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.

n n

Typical hash functions perform computation on the internal binary representation of the search-key.
l

For example, for a string search-key, the binary representations of all the characters in the string could be added and the sum modulo the number of buckets could be returned. .

Database System Concepts - 5th Edition.

12.89

Silberschatz, Korth and Sudarshan

Handling of Bucket Overflows


n

Bucket overflow can occur because of


l l

Insufficient buckets Skew in distribution of records. This can occur due to 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.

Database System Concepts - 5th Edition.

12.90

Silberschatz, Korth and Sudarshan

Handling of Bucket Overflows (Cont.)


n n

Overflow chaining the overflow buckets of a given bucket are chained together in a linked list. Above scheme is called closed hashing.
l

An alternative, called open hashing, which does not use overflow buckets, is not suitable for database applications.

Database System Concepts - 5th Edition.

12.91

Silberschatz, Korth and Sudarshan

Hash Indices
n n n

Hashing can be used not only for file organization, but also for indexstructure 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
l

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.

Database System Concepts - 5th Edition.

12.92

Silberschatz, Korth and Sudarshan

Example of Hash Index

Database System Concepts - 5th Edition.

12.93

Silberschatz, Korth and Sudarshan

Deficiencies of Static Hashing


n

In static hashing, function h maps search-key values to a fixed set of B of bucket addresses. Databases grow or shrink with time.
l

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
l

Expensive, disrupts normal operations

Better solution: allow the number of buckets to be modified dynamically.

Database System Concepts - 5th Edition.

12.94

Silberschatz, Korth and Sudarshan

Dynamic Hashing
Good for database that grows and shrinks in size n Allows the hash function to be modified dynamically n Extendable hashing one form of dynamic hashing
n
l
l l

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 = 2i. Initially i = 0

Value of i grows and shrinks as the size of the database grows and shrinks. Multiple entries in the bucket address table may point to a bucket (why?) Thus, actual number of buckets is < 2i

The number of buckets also changes dynamically due to coalescing and splitting of buckets.
12.95 Silberschatz, Korth and Sudarshan

Database System Concepts - 5th Edition.

General Extendable Hash Structure

In this structure, i2 = i3 = i, whereas i1 = i 1 (see next slide for details)


Database System Concepts - 5th Edition. 12.96 Silberschatz, Korth and Sudarshan

Use of Extendable Hash Structure


n

Each bucket j stores a value ij


l

All the entries that point to the same bucket have the same values on the first ij bits.

To locate the bucket containing search-key Kj:


1. Compute h(Kj) = 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 Kj


l l l

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 (will see shortly)

Database System Concepts - 5th Edition.

12.97

Silberschatz, Korth and Sudarshan

Insertion in Extendable Hash Structure (Cont)


To split a bucket j when inserting record with search-key value Kj:
n

If i > ij (more than one pointer to bucket j)


l

allocate a new bucket z, and set ij = iz = (ij + 1) l Update the second half of the bucket address table entries originally pointing to j, to point to z l remove each record in bucket j and reinsert (in j or z) l recompute new bucket for Kj and insert record in the bucket (further splitting is required if the bucket is still full) n If i = ij (only one pointer to bucket j) l If i reaches some limit b, or too many splits have happened in this insertion, create an overflow bucket l 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 Kj Now i > ij so use the first case above.
Database System Concepts - 5th Edition. 12.98 Silberschatz, Korth and Sudarshan

Deletion in Extendable Hash Structure


n

To delete a key value,


l l

locate it in its bucket and remove it. The bucket itself can be removed if it becomes empty (with appropriate updates to the bucket address table). Coalescing of buckets can be done (can coalesce only with a buddy bucket having same value of ij and same ij 1 prefix, if it is present) Decreasing bucket address table size is also possible

Note: decreasing bucket address table size is an expensive operation and should be done only if number of buckets becomes much smaller than the size of the table

Database System Concepts - 5th Edition.

12.99

Silberschatz, Korth and Sudarshan

Use of Extendable Hash Structure: Example

Initial Hash structure, bucket size = 2


Database System Concepts - 5th Edition. 12.100 Silberschatz, Korth and Sudarshan

Example (Cont.)
n

Hash structure after insertion of one Brighton and two Downtown records

Database System Concepts - 5th Edition.

12.101

Silberschatz, Korth and Sudarshan

Example (Cont.)
Hash structure after insertion of Mianus record

Database System Concepts - 5th Edition.

12.102

Silberschatz, Korth and Sudarshan

Example (Cont.)

Hash structure after insertion of three Perryridge records

Database System Concepts - 5th Edition.

12.103

Silberschatz, Korth and Sudarshan

Example (Cont.)
n

Hash structure after insertion of Redwood and Round Hill records

Database System Concepts - 5th Edition.

12.104

Silberschatz, Korth and Sudarshan

Extendable Hashing vs. Other Schemes


n

Benefits of extendable hashing: l Hash performance does not degrade with growth of file l Minimal space overhead

Disadvantages of extendable hashing l Extra level of indirection to find desired record l Bucket address table may itself become very big (larger than memory) Cannot allocate very large contiguous areas on disk either Solution: B+-tree file organization to store bucket address table l Changing size of bucket address table is an expensive operation n Linear hashing is an alternative mechanism l Allows incremental growth of its directory (equivalent to bucket address table) l At the cost of more bucket overflows
n

Database System Concepts - 5th Edition.

12.105

Silberschatz, Korth and Sudarshan

Comparison of Ordered Indexing and Hashing


n n n n

Cost of periodic re-organization Relative frequency of insertions and deletions Is it desirable to optimize average access time at the expense of worst-case access time? Expected type of queries:
l

Hashing is generally better at retrieving records having a specified value of the key.

If range queries are common, ordered indices are to be preferred


PostgreSQL supports hash indices, but discourages use due to poor performance Oracle supports static hash organization, but not hash indices SQLServer supports only B+-trees

In practice:
l

l l

Database System Concepts - 5th Edition.

12.106

Silberschatz, Korth and Sudarshan

Bitmap Indices
n n

Bitmap indices are a special type of index designed for efficient querying on multiple keys Records in a relation are assumed to be numbered sequentially from, say, 0
l

Given a number n it must be easy to retrieve record n

Particularly easy if records are of fixed size

Applicable on attributes that take on a relatively small number of distinct values


l l

E.g. gender, country, state, E.g. income-level (income broken up into a small number of levels such as 0-9999, 10000-19999, 20000-50000, 50000- infinity)

A bitmap is simply an array of bits

Database System Concepts - 5th Edition.

12.107

Silberschatz, Korth and Sudarshan

Bitmap Indices (Cont.)


n

In its simplest form a bitmap index on an attribute has a bitmap for each value of the attribute
l

Bitmap has as many bits as records

In a bitmap for value v, the bit for a record is 1 if the record has the value v for the attribute, and is 0 otherwise

Database System Concepts - 5th Edition.

12.108

Silberschatz, Korth and Sudarshan

Bitmap Indices (Cont.)


n

Bitmap indices are useful for queries on multiple attributes


l

not particularly useful for single attribute queries Intersection (and) Union (or) Complementation (not)

Queries are answered using bitmap operations


l l l

Each operation takes two bitmaps of the same size and applies the operation on corresponding bits to get the result bitmap
l

E.g. 100110 AND 110011 = 100010 100110 OR 110011 = 110111 NOT 100110 = 011001

Males with income level L1: 10010 AND 10100 = 10000


Can then retrieve required tuples. Counting number of matching tuples is even faster

Database System Concepts - 5th Edition.

12.109

Silberschatz, Korth and Sudarshan

Bitmap Indices (Cont.)


n

Bitmap indices generally very small compared with relation size


l

E.g. if record is 100 bytes, space for a single bitmap is 1/800 of space used by relation.

If number of distinct attribute values is 8, bitmap is only 1% of relation size

Deletion needs to be handled properly


l

Existence bitmap to note if there is a valid record at a record location

Needed for complementation

not(A=v):

(NOT bitmap-A-v) AND ExistenceBitmap

Should keep bitmaps for all values, even null value


l

To correctly handle SQL null semantics for NOT(A=v):

intersect above result with (NOT bitmap-A-Null)

Database System Concepts - 5th Edition.

12.110

Silberschatz, Korth and Sudarshan

Efficient Implementation of Bitmap Operations


n

Bitmaps are packed into words; a single word and (a basic CPU instruction) computes and of 32 or 64 bits at once
l

E.g. 1-million-bit maps can be and-ed with just 31,250 instruction Use each byte to index into a precomputed array of 256 elements each storing the count of 1s in the binary representation

Counting number of 1s can be done fast by a trick:


l

Can use pairs of bytes to speed up further at a higher memory cost

Add up the retrieved counts

Bitmaps can be used instead of Tuple-ID lists at leaf levels of B+-trees, for values that have a large number of matching records
l

Worthwhile if > 1/64 of the records have that value, assuming a tuple-id is 64 bits Above technique merges benefits of bitmap and B+-tree indices

Database System Concepts - 5th Edition.

12.111

Silberschatz, Korth and Sudarshan

Index Definition in SQL


n

Create an index create index <index-name> on <relation-name> (<attribute-list>)

E.g.: create index b-index on branch(branch_name)


n

Use create unique index to indirectly specify and enforce the condition that the search key is a candidate key is a candidate key.
l

Not really required if SQL unique integrity constraint is supported drop index <index-name>

To drop an index
Most database systems allow specification of type of index, and clustering.

Database System Concepts - 5th Edition.

12.112

Silberschatz, Korth and Sudarshan

End of Chapter

Database System Concepts, 5th Ed.


Silberschatz, Korth and Sudarshan See www.db-book.com for conditions on re-use

Partitioned Hashing
n

Hash values are split into segments that depend on each attribute of the search-key. (A1, A2, . . . , An) for n attribute search-key

Example: n = 2, for customer, search-key being (customer-street, customer-city)


search-key value (Main, Harrison) (Main, Brooklyn) (Park, Palo Alto) (Spring, Brooklyn) (Alma, Palo Alto) hash value 101 111 101 001 010 010 001 001 110 010

To answer equality query on single attribute, need to look up multiple buckets. Similar in effect to grid files.

Database System Concepts - 5th Edition.

12.114

Silberschatz, Korth and Sudarshan

Sequential File For account Records

Database System Concepts - 5th Edition.

12.115

Silberschatz, Korth and Sudarshan

Sample account File

Database System Concepts - 5th Edition.

12.116

Silberschatz, Korth and Sudarshan

Figure 12.2

Database System Concepts - 5th Edition.

12.117

Silberschatz, Korth and Sudarshan

Figure 12.14

Database System Concepts - 5th Edition.

12.118

Silberschatz, Korth and Sudarshan

Figure 12.25

Database System Concepts - 5th Edition.

12.119

Silberschatz, Korth and Sudarshan

Grid Files
n n

Structure used to speed the processing of general multiple searchkey queries involving one or more comparison operators. The grid file has a single grid array and one linear scale for each search-key attribute. The grid array has number of dimensions equal to number of search-key attributes. Multiple cells of grid array can point to same bucket To find the bucket for a search-key value, locate the row and column of its cell using the linear scales and follow pointer

n n

Database System Concepts - 5th Edition.

12.120

Silberschatz, Korth and Sudarshan

Example Grid File for account

Database System Concepts - 5th Edition.

12.121

Silberschatz, Korth and Sudarshan

Queries on a Grid File


n

A grid file on two attributes A and B can handle queries of all following forms with reasonable efficiency
l

(a1 A a2)

l
l

(b1 B b2)
(a1 A a2 b1 B b2),.

E.g., to answer (a1 A a2 b1 B b2), use linear scales to find corresponding candidate grid array cells, and look up all the buckets pointed to from those cells.

Database System Concepts - 5th Edition.

12.122

Silberschatz, Korth and Sudarshan

Grid Files (Cont.)


n

During insertion, if a bucket becomes full, new bucket can be created if more than one cell points to it.
l

Idea similar to extendable hashing, but on multiple dimensions

If only one cell points to it, either an overflow bucket must be created or the grid size must be increased

Linear scales must be chosen to uniformly distribute records across cells.


l

Otherwise there will be too many overflow buckets. But reorganization can be very expensive.

Periodic re-organization to increase grid size will help.


l

n n

Space overhead of grid array can be high. R-trees (Chapter 23) are an alternative

Database System Concepts - 5th Edition.

12.123

Silberschatz, Korth and Sudarshan

Você também pode gostar