+ All Categories
Home > Documents > Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices •...

Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices •...

Date post: 24-Feb-2021
Category:
Upload: others
View: 4 times
Download: 0 times
Share this document with a friend
58
Indexing and Hashing
Transcript
Page 1: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

IndexingandHashing

Page 2: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

Overview• BasicConcepts• OrderedIndices• B+-TreeIndexFiles• StaticHashing• DynamicHashing• ComparisonofOrderedIndexingandHashing• IndexDefinitioninSQL• Multiple-KeyAccess

Page 3: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

BasicConcepts• Indexingmechanismsusedtospeedupaccesstodesireddata.

– E.g.,authorcataloginlibrary• SearchKey- attributetosetofattributesusedtolookuprecordsin

afile.• Anindexfileconsistsofrecords(calledindexentries)oftheform

• Indexfilesaretypicallymuchsmallerthantheoriginalfile• Twobasickindsofindices:

– Orderedindices:searchkeysarestoredinsortedorder– Hashindices:searchkeysaredistributeduniformlyacross“buckets”

usinga“hashfunction”.

search-key pointer

Page 4: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

IndexEvaluationMetrics

• Accesstypessupportedefficiently.E.g.,– recordswithaspecifiedvalueintheattribute– orrecordswithanattributevaluefallinginaspecifiedrangeofvalues.

• Accesstime• Insertiontime• Deletiontime• Spaceoverhead

Page 5: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

OrderedIndices• Inanorderedindex,indexentriesarestoredsortedonthe

searchkeyvalue.E.g.,authorcataloginlibrary.• Primaryindex:inasequentiallyorderedfile,theindex

whosesearchkeyspecifiesthesequentialorderofthefile.– Alsocalledclusteringindex– Thesearchkeyofaprimaryindexisusuallybutnotnecessarily

theprimarykey.• Secondaryindex:anindexwhosesearchkeyspecifiesan

orderdifferentfromthesequentialorderofthefile.Alsocallednon-clusteringindex.

• Index-sequentialfile:orderedsequentialfilewithaprimaryindex.

Page 6: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

DenseIndexFiles

• Denseindex— Indexrecordappearsforeverysearch-keyvalueinthefile.

Page 7: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

SparseIndexFiles• SparseIndex:containsindexrecordsforonlysomesearch-

keyvalues.– Applicablewhenrecordsaresequentiallyorderedonsearch-key

• Tolocatearecordwithsearch-keyvalueKwe:– Findindexrecordwithlargestsearch-keyvalue<K– Searchfilesequentiallystartingattherecordtowhichtheindex

recordpoints

Page 8: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

SparseIndexFiles(Cont.)

• Comparedtodenseindices:– Lessspaceandlessmaintenanceoverheadforinsertionsanddeletions.

– Generallyslowerthandenseindexforlocatingrecords.

• Goodtradeoff:sparseindexwithanindexentryforeveryblockinfile,correspondingtoleastsearch-keyvalueintheblock.

Page 9: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

MultilevelIndex• Ifprimaryindexdoesnotfitinmemory,accessbecomesexpensive.

• Solution:treatprimaryindexkeptondiskasasequentialfileandconstructasparseindexonit.– outerindex– asparseindexofprimaryindex– innerindex– theprimaryindexfile

• Ifevenouterindexistoolargetofitinmainmemory,yetanotherlevelofindexcanbecreated,andsoon.

• Indicesatalllevelsmustbeupdatedoninsertionordeletionfromthefile.

Page 10: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered
Page 11: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

IndexUpdate:Deletion• Ifdeletedrecordwastheonlyrecordinthefilewithitsparticularsearch-keyvalue,thesearch-keyisdeletedfromtheindexalso.

• Single-levelindexdeletion:– Denseindices– deletionofsearch-key:similartofilerecorddeletion.

– Sparseindices–• ifanentryforthesearchkeyexistsintheindex,itisdeletedbyreplacingtheentryintheindexwiththenextsearch-keyvalueinthefile(insearch-keyorder).

• Ifthenextsearch-keyvaluealreadyhasanindexentry,theentryisdeletedinsteadofbeingreplaced.

Page 12: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

IndexUpdate:Insertion• Single-level indexinsertion:– Performalookupusingthesearch-keyvalueappearingintherecordtobeinserted.

– Denseindices– ifthesearch-keyvaluedoesnotappearintheindex,insertit.

– Sparseindices– ifindexstoresanentryforeachblockofthefile,nochangeneedstobemadetotheindexunlessanewblockiscreated.• Ifanewblockiscreated,thefirstsearch-keyvalueappearinginthenewblockisinsertedintotheindex.

• Multilevelinsertion(aswellasdeletion)algorithmsaresimpleextensionsofthesingle-levelalgorithms

Page 13: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

SecondaryIndices• Frequently,onewantstofindalltherecordswhosevaluesinacertainfield(whichisnotthesearch-keyoftheprimaryindex)satisfysomecondition.– Example1:Intheaccountrelationstoredsequentiallybyaccountnumber,wemaywanttofindallaccountsinaparticularbranch

– Example2:asabove,butwherewewanttofindallaccountswithaspecifiedbalanceorrangeofbalances

• Wecanhaveasecondaryindexwithanindexrecordforeachsearch-keyvalue

Page 14: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

SecondaryIndicesExample• Indexrecordpointstoabucketthatcontainspointerstoalltheactual

recordswiththatparticularsearch-keyvalue.• Secondaryindiceshavetobedense

Page 15: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

PrimaryandSecondaryIndices• Indicesoffersubstantialbenefitswhensearchingforrecords.

• BUT:Updatingindicesimposesoverheadondatabasemodification--whenafileismodified,everyindexonthefilemustbeupdated,

• Sequentialscanusingprimaryindexisefficient,butasequentialscanusingasecondaryindexisexpensive– Eachrecordaccessmayfetchanewblockfromdisk– Blockfetchrequiresabout5to10milliseconds

• versusabout100nanosecondsformemoryaccess

Page 16: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

B+-TreeIndexFiles• Disadvantageofindexed-sequentialfiles

– performancedegradesasfilegrows,sincemanyoverflowblocksgetcreated.

– Periodicreorganizationofentirefileisrequired.• AdvantageofB+-treeindexfiles:

– automaticallyreorganizesitselfwithsmall,local,changes,inthefaceofinsertionsanddeletions.

– Reorganizationofentirefileisnotrequiredtomaintainperformance.

• (Minor)disadvantageofB+-trees:– extrainsertionanddeletionoverhead,spaceoverhead.

• AdvantagesofB+-treesoutweighdisadvantages– B+-treesareusedextensively

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

Page 17: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

B+-TreeIndexFiles(Cont.)

• AB+-treeisarootedtreesatisfyingthefollowingproperties:– Allpathsfromroottoleafareofthesamelength– Eachnodethatisnotarootoraleafhasbetween⎡n/2⎤ andnchildren.

– Aleafnodehasbetween⎡(n–1)/2⎤ andn–1values– Specialcases:• Iftherootisnotaleaf,ithasatleast2children.• Iftherootisaleaf(thatis,therearenoothernodesinthetree),itcanhavebetween0and(n–1)values.

Page 18: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

B+-TreeNodeStructure

• Typicalnode

– Kiarethesearch-keyvalues– Piarepointerstochildren(fornon-leafnodes)orpointerstorecordsorbucketsofrecords(forleafnodes).

• Thesearch-keysinanodeareordered– K1<K2<K3<...<Kn–1

Page 19: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

LeafNodesinB+-Trees• Fori=1,2,...,n–1,pointerPieitherpointstoafilerecordwith

search-keyvalueKi,ortoabucketofpointerstofilerecords,eachrecordhavingsearch-keyvalueKi.Onlyneedbucketstructureifsearch-keydoesnotformaprimarykey.

• IfLi,Ljareleafnodesandi<j,Li’ssearch-keyvaluesarelessthanLj’ssearch-keyvalues

• Pnpointstonextleafnodeinsearch-keyorder

Page 20: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

Non-LeafNodesinB+-Trees

• Nonleafnodesformamulti-levelsparseindexontheleafnodes.Foranon-leafnodewithmpointers:– Allthesearch-keysinthesubtreetowhichP1pointsarelessthanK1

– For2≤ i≤ n– 1,allthesearch-keysinthesubtreetowhichPipointshavevaluesgreaterthanorequaltoKi–1andlessthanKi

– Allthesearch-keysinthesubtreetowhichPnpointshavevaluesgreaterthanorequaltoKn–1

Page 21: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

ExampleofaB+-tree

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

Page 22: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

ExampleofB+-tree

• Leafnodesmusthavebetween2and4values(⎡(n–1)/2⎤ andn–1,withn=5).

• Non-leafnodesotherthanrootmusthavebetween3and5children(⎡(n/2⎤ andnwithn=5).

• Rootmusthaveatleast2children.

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

Page 23: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

ObservationsaboutB+-trees• Sincetheinter-nodeconnectionsaredonebypointers,“logically” closeblocksneednotbe“physically” close.

• Thenon-leaflevelsoftheB+-treeformahierarchyofsparseindices.

• TheB+-treecontainsarelativelysmallnumberoflevels– Levelbelowroothasatleast2*⎡n/2⎤ values– Nextlevelhasatleast2*⎡n/2⎤ *⎡n/2⎤ values– IfthereareKsearch-keyvaluesinthefile,thetreeheightisno

morethan⎡log⎡n/2⎤(K)⎤– thussearchescanbeconductedefficiently.

• Insertionsanddeletionstothemainfilecanbehandledefficiently,astheindexcanberestructuredinlogarithmictime(asweshallsee).

Page 24: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

QueriesonB+-Trees• Findallrecordswithasearch-keyvalueofk.

– N=root– Repeat

• ExamineNforthesmallestsearch-keyvalue>k.• Ifsuchavalueexists,assumeitisKi.ThensetN=Pi• Otherwisek≥ Kn–1.SetN=Pn• UntilNisaleafnode

– Ifforsomei,keyKi=kfollowpointerPitothedesiredrecordorbucket.

– Elsenorecordwithsearch-keyvaluekexists.

Page 25: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

QueriesonB+-Trees(Cont.)• IfthereareKsearch-keyvaluesinthefile,theheightofthe

treeisnomorethan⎡log⎡n/2⎤(K)⎤.• Anodeisgenerallythesamesizeasadiskblock,typically4

kilobytes– andnistypicallyaround100(40bytesperindexentry).

• With1millionsearchkeyvaluesandn=100– atmostlog50(1,000,000)=4nodesareaccessedinalookup.

• Contrastthiswithabalancedbinarytreewith1millionsearchkeyvalues— around20nodesareaccessedinalookup– abovedifferenceissignificantsinceeverynodeaccessmayneed

adiskI/O,costingaround20milliseconds

Page 26: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

UpdatesonB+-Trees:Insertion• Findtheleafnodeinwhichthesearch-keyvaluewould

appear• Ifthereisroomintheleafnode,insert(key-value,

pointer)pairintheleafnode• Otherwise,splitthenode(alongwiththenew(key-value,

pointer)entry)asdiscussedinthenextslide.

Page 27: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

UpdatesonB+-Trees:Insertion(Cont.)

• Splittingaleafnode:– takethen(search-keyvalue,pointer)pairs(includingtheonebeing

inserted)insortedorder.Placethefirst⎡n/2⎤ intheoriginalnode,andtherestinanewnode.

– letthenewnodebep,andletkbetheleastkeyvalueinp.Insert(k,p)intheparentofthenodebeingsplit.

– Iftheparentisfull,splititandpropagatethesplitfurtherup.• Splittingofnodesproceedsupwardstillanodethatisnotfullis

found.– Intheworstcasetherootnodemaybesplitincreasingtheheightof

thetreeby1.

Page 28: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

UpdatesonB+-Trees:Insertion(Cont.)

B+-Tree before and after insertion of “Clearview”

Page 29: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

UpdatesonB+-Trees:Deletion

• Findtherecordtobedeleted,andremoveitfromthemainfileandfromthebucket(ifpresent)

• Remove(search-keyvalue,pointer)fromtheleafnodeifthereisnobucketorifthebuckethasbecomeempty

• Ifthenodehastoofewentriesduetotheremoval,andtheentriesinthenodeandasiblingfitintoasinglenode,thenmergesiblings

Page 30: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

UpdatesonB+-Trees:Deletion• Otherwise,ifthenodehastoofewentriesduetotheremoval,buttheentriesinthenodeandasiblingdonotfitintoasinglenode,thenredistributepointers:– Redistributethepointersbetweenthenodeandasiblingsuchthatbothhavemorethantheminimumnumberofentries.

– Updatethecorrespondingsearch-keyvalueintheparentofthenode.

• Thenodedeletionsmaycascadeupwardstillanodewhichhas⎡n/2⎤ ormorepointersisfound.

• Iftherootnodehasonlyonepointerafterdeletion,itisdeletedandthesolechildbecomestheroot.

Page 31: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

ExamplesofB+-TreeDeletion

Before and after deleting “Downtown”

Page 32: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

ExamplesofB+-TreeDeletion

Deletion of “Perryridge” from result of previous example

Page 33: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

ExampleofB+-treeDeletion

Before and after deletion of “Perryridge” from earlier example

Page 34: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

Multiple-KeyAccess• Usemultipleindicesforcertaintypesofqueries.• Example:

selectaccount_numberfromaccountwherebranch_name=“Perryridge” andbalance=1000

• Possiblestrategiesforprocessingqueryusingindicesonsingleattributes:1. Useindexonbranch_nametofindaccountswithbranchname

Perryridge;testbalance=10002. Useindexonbalancetofindaccountswithbalancesof$1000;test

branch_name=“Perryridge”.3. Usebranch_nameindextofindpointerstoallrecordspertainingto

thePerryridgebranch.Similarlyuseindexonbalance.Takeintersectionofbothsetsofpointersobtained.

Page 35: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

IndicesonMultipleKeys• Compositesearchkeysaresearchkeyscontainingmorethanoneattribute– E.g.(branch_name,balance)

• Lexicographicordering:(a1,a2)<(b1,b2)ifeither– a1<b1,or– a1=b1anda2<b2

• Canalsoefficientlyhandlewherebranch_name=“Perryridge” andbalance<1000

• Butcannotefficientlyhandlewherebranch_name<“Perryridge” andbalance=1000

Page 36: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

Non-UniqueSearchKeys

• Alternatives:– Makesearchkeyuniquebyaddingarecord-identifier• Extrastorageoverheadforkeys• Simplercodeforinsertion/deletion• Widelyused

Page 37: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

OtherIssuesinIndexing• Coveringindices

– Addextraattributestoindexso(some)queriescanavoidfetchingtheactualrecords• Particularlyusefulforsecondaryindices

– Canstoreextraattributesonlyatleaf• Recordrelocationandsecondaryindices

– Ifarecordmoves,allsecondaryindicesthatstorerecordpointershavetobeupdated

– NodesplitsinB+-treefileorganizationsbecomeveryexpensive– Solution:useprimary-indexsearchkeyinsteadofrecordpointer

insecondaryindex• Extratraversalofprimaryindextolocaterecord

– Highercostforqueries,butnodesplitsarecheap• Addrecord-idifprimary-indexsearchkeyisnon-unique

Page 38: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

Hashing

Page 39: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

StaticHashing• Abucketisaunitofstoragecontainingoneormorerecords(abucketistypicallyadiskblock).

• Inahashfileorganizationweobtainthebucketofarecorddirectlyfromitssearch-keyvalueusingahashfunction.

• Hashfunctionhisafunctionfromthesetofallsearch-keyvaluesKtothesetofallbucketaddressesB.

• Hashfunctionisusedtolocaterecordsforaccess,insertionaswellasdeletion.

• Recordswithdifferentsearch-keyvaluesmaybemappedtothesamebucket;thusentirebuckethastobesearchedsequentiallytolocatearecord.

Page 40: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

ExampleofHashFileOrganization

• Hashfileorganizationofaccount file,usingbranch_nameaskey– Thereare10buckets,– E.g.h(Perryridge)=5h(RoundHill)=3h(Brighton)=3

Page 41: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

HashFunctions• Worsthashfunctionmapsallsearch-keyvaluestothesamebucket;thismakesaccesstimeproportionaltothenumberofsearch-keyvaluesinthefile.

• Anidealhashfunctionisuniform,i.e.,eachbucketisassignedthesamenumberofsearch-keyvaluesfromthesetofallpossiblevalues.

• Idealhashfunctionisrandom,soeachbucketwillhavethesamenumberofrecordsassignedtoitirrespectiveoftheactualdistributionofsearch-keyvaluesinthefile.

Page 42: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

HandlingofBucketOverflows

• Bucketoverflowcanoccurbecauseof– Insufficientbuckets– Skewindistributionofrecords.Thiscanoccurduetotworeasons:• multiplerecordshavesamesearch-keyvalue• chosenhashfunctionproducesnon-uniformdistributionofkeyvalues

• Althoughtheprobabilityofbucketoverflowcanbereduced,itcannotbeeliminated;itishandledbyusingoverflowbuckets.

Page 43: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

HandlingofBucketOverflows(Cont.)

• Overflowchaining– theoverflowbucketsofagivenbucketarechainedtogetherinalinkedlist.

Page 44: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

HashIndices• Hashingcanbeusednotonlyforfileorganization,butalsoforindex-structurecreation.

• Ahashindexorganizesthesearchkeys,withtheirassociatedrecordpointers,intoahashfilestructure.

• Strictlyspeaking,hashindicesarealwayssecondaryindices– ifthefileitselfisorganizedusinghashing,aseparateprimaryhashindexonitusingthesamesearch-keyisunnecessary.

– However,weusethetermhashindextorefertobothsecondaryindexstructuresandhashorganizedfiles.

Page 45: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

ExampleofHashIndex

Page 46: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

DeficienciesofStaticHashing• Instatichashing,functionhmapssearch-keyvaluestoa

fixedsetofBofbucketaddresses.Databasesgroworshrinkwithtime.– Ifinitialnumberofbucketsistoosmall,andfilegrows,

performancewilldegradeduetotoomuchoverflows.– Ifspaceisallocatedforanticipatedgrowth,asignificantamount

ofspacewillbewastedinitially(andbucketswillbeunderfull).– Ifdatabaseshrinks,againspacewillbewasted.

• Onesolution:periodicre-organizationofthefilewithanewhashfunction– Expensive,disruptsnormaloperations

• Bettersolution:allowthenumberofbucketstobemodifieddynamically.

Page 47: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

Initial Hash structure, bucket size = 2

Page 48: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered
Page 49: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered
Page 50: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

ExtendableHashingvs.OtherSchemes

• Benefitsofextendablehashing:– Hashperformancedoesnotdegradewithgrowthoffile

– Minimalspaceoverhead• Disadvantagesofextendablehashing– Extralevelofindirectiontofinddesiredrecord– Bucketaddresstablemayitselfbecomeverybig(largerthanmemory)• Cannotallocateverylargecontiguousareasondiskeither• Solution:B+-treestructuretolocatedesiredrecordinbucketaddresstable

Page 51: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

ComparisonofOrderedIndexingandHashing

• Costofperiodicre-organization• Relativefrequencyofinsertionsanddeletions• Isitdesirabletooptimizeaverageaccesstimeattheexpenseof

worst-caseaccesstime?• Expectedtypeofqueries:

– Hashingisgenerallybetteratretrievingrecordshavingaspecifiedvalueofthekey.

– Ifrangequeriesarecommon,orderedindicesaretobepreferred• Inpractice:

– PostgreSQLsupportshashindices,butdiscouragesuseduetopoorperformance

– Oraclesupportsstatichashorganization,butnothashindices– SQLServersupportsonlyB+-trees

Page 52: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

BitmapIndices• Bitmapindicesareaspecialtypeofindexdesignedfor

efficientqueryingonmultiplekeys• Recordsinarelationareassumedtobenumbered

sequentiallyfrom,say,0– Givenanumbernitmustbeeasytoretrieverecordn

• Particularlyeasyifrecordsareoffixedsize• Applicableonattributesthattakeonarelativelysmall

numberofdistinctvalues– E.g.gender,country,state,…– E.g.income-level(incomebrokenupintoasmallnumberof

levelssuchas0-9999,10000-19999,20000-50000,50000-infinity)

• Abitmapissimplyanarrayofbits

Page 53: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

BitmapIndices(Cont.)• Initssimplestformabitmapindexonanattributehasabitmapforeachvalueoftheattribute– Bitmaphasasmanybitsasrecords– Inabitmapforvaluev,thebitforarecordis1iftherecordhasthevaluevfortheattribute,andis0otherwise

Page 54: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

BitmapIndices(Cont.)• Bitmapindicesareusefulforqueriesonmultipleattributes

– notparticularlyusefulforsingleattributequeries• Queriesareansweredusingbitmapoperations

– Intersection(and)– Union(or)– Complementation(not)

• Eachoperationtakestwobitmapsofthesamesizeandappliestheoperationoncorrespondingbitstogettheresultbitmap– E.g.100110AND110011=100010– 100110OR110011=110111

NOT100110=011001– MaleswithincomelevelL1:10010AND10100=10000

• Canthenretrieverequiredtuples.• Countingnumberofmatchingtuplesisevenfaster

Page 55: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

BitmapIndices(Cont.)• Bitmapindicesgenerallyverysmallcomparedwithrelation

size– E.g.ifrecordis100bytes,spaceforasinglebitmapis1/800of

spaceusedbyrelation.• Ifnumberofdistinctattributevaluesis8,bitmapisonly1%ofrelationsize

• Deletionneedstobehandledproperly– Existencebitmaptonoteifthereisavalidrecordatarecord

location– Neededforcomplementation

• not(A=v):(NOTbitmap-A-v)ANDExistenceBitmap• Shouldkeepbitmapsforallvalues,evennullvalue

– TocorrectlyhandleSQLnullsemanticsforNOT(A=v):• intersectaboveresultwith(NOTbitmap-A-Null)

Page 56: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

EfficientImplementationofBitmapOperations

• Bitmapsarepackedintowords;asinglewordand(abasicCPUinstruction)computesandof32or64bitsatonce– E.g.1-million-bitmapscanbeand-edwithjust31,250instruction

• Countingnumberof1scanbedonefastbyatrick:– Useeachbytetoindexintoaprecomputedarrayof256elementseach

storingthecountof1sinthebinaryrepresentation• Canusepairsofbytestospeedupfurtheratahighermemorycost

– Adduptheretrievedcounts• BitmapscanbeusedinsteadofTuple-IDlistsatleaflevelsof

B+-trees,forvaluesthathavealargenumberofmatchingrecords– Worthwhileif>1/64oftherecordshavethatvalue,assumingatuple-

idis64bits– AbovetechniquemergesbenefitsofbitmapandB+-treeindices

Page 57: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

IndexDefinitioninSQL• Createanindex

– createindex<index-name>on<relation-name>(<attribute-list>)

– E.g.:createindexb-indexonbranch(branch_name)• Usecreateuniqueindextoindirectlyspecifyandenforce

theconditionthatthesearchkeyisacandidatekeyisacandidatekey.– NotreallyrequiredifSQLuniqueintegrityconstraintis

supported• Todropanindex

– dropindex<index-name>• Mostdatabasesystemsallowspecificationoftypeofindex,

andclustering.

Page 58: Indexing and Hashingnzhang10/6907/files/d1.pdfOverview • Basic Concepts • Ordered Indices • B+-Tree Index Files • Static Hashing • Dynamic Hashing • Comparison of Ordered

EndofChapter


Recommended