Sub topic 6
Hashed files: equality lookups and their limits
This chapter assumes you know blocking factor and block counts (from the earlier chapters on records and blocks) and the costs of heap and sorted files. It also assumes you can read basic modular arithmetic and a short Python class. Cost is always counted in block accesses.
The idea
A hashed file (also called a direct file) stores each record in a place computed from its key. A hash function h(K) turns the key K into a bucket number between 0 and M-1. Here M is the number of buckets. A bucket is one disk block, or a small group of blocks, that holds the records with that hash value.
To find a record, you do not search. You compute h(K), read that bucket, and look inside the block in memory. The cost does not depend on the file size, so the ideal cost is 1 block access.
A common choice is h(K) = K mod M, with M a prime number so the keys spread evenly. For text keys, the characters are first combined into an integer.
Sizing a static hashed file
In static hashing, M is fixed when the file is created. Choose M so the buckets are only partly full. The load factor is the fraction of the bucket space actually used. A typical target is 70 to 80 percent.
Take 30,000 records with a blocking factor of 10, and aim for 80 percent full buckets.
- Blocks of data needed: 30000 / 10 = 3000.
- Buckets: M = ceil(3000 / 0.8) = 3750.
Now compare equality search costs for this file:
| Organisation | Block accesses to find one record by key |
|---|---|
| Heap file | 3000 / 2 = 1500 on average, 3000 worst case |
| Sorted file (binary search) | ceil(log2 3000) = 12 |
| Hashed file | about 1 (more if the bucket has overflow) |
The hashed file wins by a wide margin, but only for this one kind of query.
Collisions and overflow
A collision happens when two different keys hash to the same bucket. Collisions are normal. They only become a problem when a bucket receives more records than one block holds. The extra records go to overflow blocks.
Common ways to handle overflow:
- Chaining. Overflow blocks are linked to the primary block by a pointer. A search follows the chain. This is the usual choice in textbooks and GATE questions.
- Open addressing. The record goes into the next free slot. This suits in-memory tables more than disk files.
- Multiple hashing. A second hash function is applied if the first bucket is full.
Chaining makes the cost for a key equal to the position of its block in the chain. A long chain makes lookups slow, and a bad hash function or a file that has outgrown M causes long chains.
Simulating a hashed file
This program builds a small static hash file with chaining and counts the block accesses of each operation.
class HashFile:
def __init__(self, num_buckets, bfr):
self.M = num_buckets
self.bfr = bfr
# each bucket is a chain of blocks; each block is a list of keys
self.buckets = [[[]] for _ in range(num_buckets)]
def _h(self, key):
return key % self.M
def insert(self, key):
chain = self.buckets[self._h(key)]
accesses = 0
for block in chain:
accesses += 1
if len(block) < self.bfr:
block.append(key)
return accesses
chain.append([key]) # allocate a new overflow block
return accesses + 1
def search(self, key):
accesses = 0
for block in self.buckets[self._h(key)]:
accesses += 1
if key in block:
return True, accesses
return False, accesses
def total_blocks(self):
return sum(len(chain) for chain in self.buckets)
f = HashFile(num_buckets=4, bfr=2)
for k in [8, 12, 16, 20, 24, 3, 7, 5]:
f.insert(k)
print(f.search(5)) # (True, 1)
print(f.search(24)) # (True, 3) third block of bucket 0
print(f.search(28)) # (False, 3) an unsuccessful search reads the whole chain
print(f.total_blocks())Keys 8, 12, 16, 20 and 24 all hash to bucket 0, so that bucket grows a chain of three blocks. Key 5 sits alone in bucket 1 and costs one access. Note that an unsuccessful search must read the entire chain, so it is the worst case for the bucket.
What a hashed file cannot do
Hashing destroys the order of the keys. Neighbouring keys such as 100 and 101 land in unrelated buckets. This gives the main limits:
- Range queries are expensive. A query like
key BETWEEN 100 AND 200has no bucket to go to. You must scan every bucket, which in the example above means all 3750 buckets. - No ordered retrieval.
ORDER BYneeds a separate sort. - Only the hash field helps. Searching on any other field is a full scan, just as with a heap file.
- Partial keys do not work. With a composite key hashed as a whole, you need every part of the key to compute the hash.
- Prefix and pattern searches fail.
LIKE 'Ra%'cannot use the hash.
Insertion, deletion and the cost of change
Insertion hashes the key, reads the bucket (following the chain to a block with space), and writes the block back. The cost is about 2 block accesses: one read and one write. Deletion is similar. It finds the record, removes it, and writes the block. If the file uses overflow chains, the freed space can be reused or the chain compacted.
Static hashing has a sizing problem:
- If M is too small, chains grow and every lookup slows down.
- If M is too large, most buckets sit mostly empty and disk space is wasted.
- Changing M means rehashing every record into a new file, which is expensive.
Dynamic hashing
Dynamic hashing lets the file grow and shrink without a full reorganisation. Two well-known schemes appear in textbooks.
Extendible hashing keeps a directory of bucket pointers, indexed by the first d bits of the hash value. The number d is the global depth. When a bucket overflows, it splits in two. If its local depth already equals the global depth, the directory doubles first. Lookups cost one directory access (free if the directory is in memory) plus one bucket access.
Linear hashing needs no directory. It splits buckets in a fixed round-robin order, whether or not the overflowing bucket is the next one to split. It handles overflow with chains until the split pointer reaches that bucket.
Both schemes keep the one-access lookup for equality search while the file changes size. Neither restores order, so range queries still need another structure. That is why the chapters that follow turn to tree indexes.
Choosing between organisations
| Need | Better choice |
|---|---|
| Many exact-key lookups, few range queries | Hashed file |
| Range queries or ordered output | Sorted file or tree index |
| Bulk loading, scanning everything | Heap file |
| Unpredictable file size with equality lookups | Dynamic hashing |
Common errors
- Saying a hashed file always costs exactly 1 access. It costs 1 only when no overflow is involved.
- Forgetting that an unsuccessful search reads the entire chain.
- Dividing by the load factor the wrong way. Buckets = blocks needed / load factor, so a lower load factor means more buckets.
- Using a hashed file to answer a range query, or a query on a non-hash field.
Exercise
A file has 12,000 records and a blocking factor of 8. It is stored as a static hashed file with a bucket holding one block, and you want an average load factor of 75 percent. (a) How many buckets M should you use? (b) How many block accesses does a range query on the hash key need, ignoring overflow? (c) How many accesses does an average equality search need if there is no overflow, compared with a sorted file of the same data?
Show answer
(a) Data blocks = 12000 / 8 = 1500. M = ceil(1500 / 0.75) = 2000 buckets. (b) A range query cannot use the hash function, so it reads every bucket: 2000 block accesses. (c) The hashed file needs 1 block access. The sorted file occupies 1500 blocks, so binary search needs ceil(log2 1500) = 11 accesses.