版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Physical&DigitalSpaceInteractionConsidermovingapencil…PhysicalspacemovementmappingtodigitalspaceDigitalspacemovementmappingtophysicalspaceWhichoneismoredifficult?TheActuatedWorkbench(MITmedialab)1CourseAdministrationAssignment#2:due11/2Assignment#3:postonthecoursehomepageDue11/8(nextTuesday)PracticumAssignment#1:Postonthecoursehomepageon11/7NextWeekReading:Chapter92ReflectionHowtodesignadatabase?Conceptualdesign:ERModelLogicaldesign:RelationalModelHowtoaskquestionsonadatabase?RelationalAlgebra&SQLsWhat’snext?Howtogetfastaccesstorecords?Fileorganizations&indexesWhat’sfurthernext?Howtooptimizequeryprocessingtime?3OverviewofStorage&IndexingChapter84OutlineTypesofexternalstoragedevicesFileorganizationsQuestions:Howtostoretablerecordsonexternalstoragedevice(e.g.,adisk)?Howtospeedupaccesstoneededrecordsonadisk?Heapfile,SortedfileIndexingdatastructuresTree-basedindexing,Hash-basedindexingComparisononfileorganizationsQuestion:whichoneisbetter/worseinperformance?IndexesandPerformanceQuestion:howtouseindexingforbetterperformance?5DataonExternalStorageExternalStorage:offerpersistentdatastorageUnlikephysicalmemory,datasavedonapersistentstorageisnotlostwhenthesystemshutdownsorcrashes.6TypesofExternalStorageDevicesMagneticDisks:Canretrieverandompageatfixedcost~$1perGigabyteButreadingseveralconsecutivepagesismuchcheaperthanreadingtheminrandomorderTapes:Canonlyreadpagesinsequence$0.3perGigabyteCheaperthandisks;usedforarchivalstorageOthertypesofpersistentstoragedevices:Opticalstorage(CD-R,CD-RW,DVD-R,DVD-RW)Flashmemory7DefinitionArecordisatupleorarowinarelationtable.Fixed-sizerecordsorvariable-sizerecordsAfileisacollectionofrecords.Storeonetableperfile,ormultipletablesinthesamefileApageisafixedlengthblockofdatafordiskI/O.Afileisconsistedofpages.Adatapagealsocontainsacollectionofrecords.Typicalpagesizesare4and8KB.8FileOrganizationMethodofarrangingafileofrecordsonexternalstorage.Recordid(rid)isusedtolocatearecordonadisk[pageid,slotnumber]Indexesaredatastructurestoefficientlysearchridsofgivenvalues9DBStorageandIndexingLayeredArchitectureDiskSpaceManagerallocates/de-allocatesspacesondisks.Buffermanagermovespagesbetweendisksandmainmemory.Fileandindexlayersorganizerecordsonfiles,andmanagetheindexingdatastructure.10AlternativeFileOrganizationsManyalternativesexist,eachidealforsomesituations,andnotsogoodinothers:Heapfiles:Recordsareunsorted.Suitablewhentypicalaccessisafilescanretrievingallrecordswithoutanyorder.Fastupdate(insertions/deletions)SortedFiles:Recordsaresorted.Bestifrecordsmustberetrievedinsomeorder,oronlya`range’ofrecordsisneeded.Examples:employeesaresortedbyage.Slowupdateincomparisontoheapfile.Indexes:Datastructurestoorganizerecordsviatreesorhashing.Forexample,createanindexonemployeeage.Likesortedfiles,speedupsearchesforasubsetofrecordsthatmatchvaluesincertain(“searchkey”)fieldsUpdatesaremuchfasterthaninsortedfiles.11IndexesAnindexonafilespeedsupselectionsonthesearchkeyfieldsfortheindex.Anysubsetoftheattributesofatablecanbethesearchkeyforanindexontherelation.SearchkeydoesnothavetobecandidatekeyExample:employeeageisnotacandidatekey.Anindexfilecontainsacollectionofdataentries(calledk*).Quicklysearchanindextolocateadataentrywithakeyvaluek.Exampleofadataentry:<age,rid>Canusethedataentrytofindthedatarecord.Exampleofadatarecord:<name,age,salary>Cancreatemultipleindexesonthesamedatarecords.Exampleindexes:age,salary,name12IndexingExampleIndexDataStructure:Indexentries+IndexingmethodDataentriesDatarecordsSearchkeyvalue:findemployeeswithage=25IndexFile(Smallforefficientsearch)DataFile(Large)Paul(k=25,Paul’srid)(B+Tree)(Hash)Mary13AlternativesforDataEntryk*Threealternativesforwhattostoreinadataentry:(Alternative1):DatarecordwithkeyvaluekExampledatarecord=dataentry:<age,name,salary>(Alternative2):<k,ridofdatarecordwithsearchkeyvaluek>Exampledataentry:<age,rid>(Alternative3):<k,listofridsofdatarecordswithsearchkeyk>Exampledataentry:<age,rid_1,rid_2,…>Choiceofalternativefordataentriesisindependentoftheindexingmethod.Indexingmethodtakesasearchkeyandfindsthedataentriesmatchingthesearchkey.Examplesofindexingmethods:B+treesorhashing.14AlternativesforDataEntries(Contd.)Alternative1:datarecordwithkeyvaluekDataentriesarealsothedatarecords.AtmostoneindexonagivencollectionofdatarecordscanuseAlternative1.Ifdatarecordsareverylarge,#ofpagescontainingdataentriesishigh.Mayleadtolessefficientsearch.15AlternativesforDataEntries(Contd.)Alternative2:<k,ridwithkeyvaluek>Alternative3:<k,rid-listofdatarecord(s)>Dataentriestypicallymuchsmallerthandatarecords.MayleadtomoreefficientsearchthanAlternative1.Why?Alternative3morecompactthanAlternative2,Leadtovariablesizeddataentries(sizeofrid-listisnotfixed)16IndexClassificationClusteredvs.unclustered:Iforderofdatarecordsisthesameas,orclosetotheorderofdataentries,thenitiscalledclusteredindex.Alternative1impliesclustered;inpractice,clusteredalsoimpliesAlternative1.OneclusteredindexandmultipleunclusteredindexesWhyisthisimportant?Considerthecostofrangesearchquery:findallrecords30<age<39[nextslide]17Clusteredvs.UnclusteredIndexCostofretrievingdatarecordsthroughindexvariesgreatlybasedonwhetherindexisclusteredornot!Examples:retrievealltheemployeesofages30~39.Whatistheworst-casecost(#diskpageI/Os)ofclusteredindex?Whatistheworst-casecostofunclusteredindex?Cost=numberofpagesretrievedmr=#matchedrecords;mp=#pagescontainingmatchedrecordsIndexentriesDataentries(IndexFile)(Datafile)DataRecordsDataentriesDataRecordsCLUSTEREDUNCLUSTEREDAges=30~39Ages=30~3918Hash-BasedIndexesGoodforequalityselections.Dataentries(key,rid)aregroupedintobuckets.Bucket=primarypagepluszeroormoreoverflowpages.Hashingfunction
h:h(r)=bucketinwhichrecordrbelongs.hlooksatthesearchkeyfieldsofr.IfAlternative(1)
isused,thebucketscontainthedatarecords.HSmith,44,30005004--300030005004Jones,40,6003Tracy,44,5004PrimarypageOverflowpageBucketASalaryAshby,25,3000Basu,33,4003Bristow,29,2019datarecordsH(salary)=AdataentriesHAgeH(age)=00H(age)=0119Hash-basedIndexes(Cont)Searchonkeyvalue:Applykeyvaluetothehashfunction->bucketnumberRetrievetheprimarypageofthebucket.Searchrecordsintheprimarypage.Ifnotfound,searchtheoverflowpages.Costoflocatingrids:#pagesinbucket(small)Insertarecord:Applykeyvaluetothehashfunction->bucketnumberIfall(primary&overflow)pagesinthatbucketarefull,allocateanewoverflowpage.Cost:similartosearch.DeletearecordCost:Similartosearch.20B+TreeIndexesLeafpagescontaindataentries,andarechained(prev&next)Non-leafpagescontainindexentriesanddirectsearches:P0K1P1K2P2KmPmindexentryNon-leafPagesPagesLeaf21ExampleB+TreeFind7*,29*?15*<age<30*Insert/delete:Finddataentryinleaf,thenchangeit.Needtoadjustparentsometimes.Andchangesometimesbubblesupthetree(keepthetreebalance)Moredetailsabouttree-basedindexinChapter10.Root1730135272*3*14*16*33*34*38*39*7*5*8*22*24*27*29*Entries<=17Entries>1722CostModelforOurAnalysisIgnoreCPUcosts,forsimplicity.MeasurediskI/Ocosts:numberofpageI/O’sIgnoresgainsofpre-fetchingasequenceofpagesCostanalysisB:ThenumberofdatapagesR:Numberofrecordsperpage
Goodenoughtoshowtheoveralltrends!23ComparingFileOrganizationsHeapfiles(randomorder;insertateof)Sortedfiles,sortedon<age,salary>
ClusteredB+treefile,Alternative(1),searchkey<age,salary>HeapfilewithunclusteredB+treeindexonsearchkey<age,salary>Heapfilewithunclusteredhashindexonsearchkey<age,salary>24OperationstoCompareScan:FetchallrecordsfromdiskEqualitysearchExample:findallemployeeswithage=23andsalary=5000.RangeselectionExample:findallemployeeswithage>35.InsertarecordIdentifythepageforinsertingtherecord,fetchit,modifyit,andwriteitback.DeletearecordSimilartoinsert.25AssumptionsinOurAnalysisHeapFiles:Equalityselectiononkey;exactlyonematch.SortedFiles:Filescompactedafterdeletions.Indexes:Alt(2),(3):dataentrysize=10%sizeofdatarecord26HeapFilesB:ThenumberofdatapagesR:NumberofrecordsperpageScan:BSearchwithequalityselection:½BSearchwithrangeselection:BInsert:2Newrecordisinsertedattheendofthefile.Read/writeoutlastpage.Deletearecord:searchcost+1(nocompacting)Deletearecord(withrid):2searchcost=1234161475813224272911211508394327SortedFilesB:ThenumberofdatapagesR:NumberofrecordsperpageScan:BSearchwithequalityselection:log2(B)BinarysearchSearchwithrangeselection:log2(B)+#pagesofmatchedrecords14<x<60:Searchforfirstmatchingrecord/page,thenfindallthequalifyingrecords/pagesinsequentialorder.Insert:searchcost+BFindtherightposition/page(search),makespacefortheinsertingrecordbyshiftingallsubsequentrecordsbyoneslot,theninsert.Delete:searchcost+BSearchtherecord,deleteit,shiftallsubsequentrecordsbyoneslot.2416231311145153647055622650155828ClusteredB+TreeFileB:ThenumberofdatapagesR:NumberofrecordsperpageScan:1.5BSearchwithequalityselection:logF(1.5B)FisnumberofchildrenperB+treenodeSearchwithrangeselection:logF(1.5B)+#pagesofmatchedrecordsSearchforfirstmatchingrecord(page),thenfindallthequalifyingrecords/pagesinsequentialorder.Un-occupancyinclusteredfile~0.5BIndexentriesDataentries=DatarecordsCLUSTERED29ClusteredB+TreeFileB:ThenumberofdatapagesR:NumberofrecordsperpageInsert:searchcost+1Findtherightposition(page),insert+writeoutthemodifiedpage.Noneedtoshiftrecords->emptydataentriesinmodifiedpage.Delete:searchcost+1Searchrecord,deleterecord,andwritebackmodifiedpage.Noneedtoshift.
IndexentriesDataentries=DatarecordsCLUSTERED30HeapFilewithUnclusteredTreeIndexB:ThenumberofdatapagesR:NumberofrecordsperpageScan(in-order):0.1B+RBUnorderscan:BSearchwithequalityselection:logF(0.1B)+1SearchfordataentrytakeslogF(0.1B)pages+onereadondatarecordpage.
Data/indexentrysize~0.1datarecordsizeUNCLUSTEREDDataentriesDataRecords31HeapFilewithUnclusteredTreeIndexB:ThenumberofdatapagesR:NumberofrecordsperpageSearchwithrangeselection:logF(0.1B)+#pagesofmatchedrecordsSearchforfirstmatchingdataentry,thenfindallthequalifyingentriesinsequentialorder.Buteachdataentrymaypointtoadatarecordonadifferentdatapage.Insert:searchcost+3Oneread/writetoheapfilepage+search+onewritetodataentrypage.Delete:searchcost+3DataentriesDataRecords32HeapFilewithUnclusteredHashIndexB:ThenumberofdatapagesR:NumberofrecordsperpageScan(in-order):0.125B+RB=(0.125+R)BUnorderscan:BSearchwithequalityselection:2Hashfunction+readdataentrypage+readdatarecordpageSearchwithrangeselection:BHashfunctionisuseless,dounorderscan.Hash:Nooverflowbuckets.80%pageoccupancy=>#dataentrypages=0.125BHSmith,44,30005004--300030005004Jones,40,6003Tracy,44,5004PrimarypageOverflowpageBucketASalaryAshby,25,3000Basu,33,4003Bristow,29,2019datarecordsH(salary)=Adataentries33HeapFilewithUnclusteredHashIndexB:ThenumberofdatapagesR:NumberofrecordsperpageInsert:4Read&WriteHeapfilepage+Read&WritedataentrypageDelete:4Hash:Nooverflowbuckets.80%pageoccupancy=>#dataentrypages=0.125BHSmith,44,30005004--300030005004Jones,40,6003Tracy,44,5004PrimarypageOverflowpageBucketASalaryAshby,25,3000Basu,33,4003Bristow,29,2019datarecordsH(salary)=Adataentries34CostofOperationsNoonefileorganizationsisuniformlysuperior(a)Scan(b)Equality(c)Range(d)Insert(e)delete(1)HeapB0.5BB2Search+1(2)SortedBlog2(B)log2(B)+#matchesSearch+BSearch+B(3)ClusteredTreeIndex1.5BlogF(1.5B)logF(1.5B)+#matchesSearch+1Search+1(4)UnclusteredTreeindexB(R+0.1)1+logF(0.1B)logF(0.1B)+#matchesSearch+3Search+3(5)UnclusteredHashIndexB(R+0.125)2B4435GeneralGuidelinesAnindexsupportsefficientretrievalofdataentriessatisfyingaselectioncondition:Twotypesofselections:equalityandrangeHash-basedindexingisonlyoptimizedforequalityselection,uselessforrangeselection.Tree-basedindexingisbetterforboth.Tree-basedclusteringindexisbestforrangeselection.36GeneralGuidelines(Cont)Clusteredindexcanbemoreexpensivethanunclusteredindex:Wheninsertinganewrecordintoafullpage,shiftexistingrecordsintootherpages→changedataentriesfortheserecords→expensive.Tradeoffformoreefficientrangeselection.37UnderstandingtheWorkloadHowtodecidethebestindexingforatable?NeedtounderstandtheworkloadForeachqueryintheworkload:Whichtablesdoesitaccess?Whichfieldsareretrieved?Whichfieldsareinvolvedinselection/joinconditions?Howselectivearetheseconditionslikelytobe?Foreachupdateintheworkload:Whichfieldsareinvolvedinselection/joinconditions?Howselectivearetheseconditionslikelytobe?Thetypeofupdate(INSERT/DELETE/UPDATE),andthefieldsthatareaffected.38ChoiceofIndexesWhatindexesshouldwecreate?Whichtablesshouldhaveindexes?Whatfield(s)shouldbethesearchkey?Shouldwebuildseveralindexes?Foreachindex,whatkindofanindexshoulditbe?Clusteredorunclustered?HashindexorTreeindex?39ChoiceofIndexes(Contd.)Oneapproach:Considerthemostimportantqueriesinturn.Considerthebestplanusingthecurrentindexes,andseeifabetterplanispossiblewithanadditionalindex.Ifso,createit.Obviously,thisimpliesthatwemustunderstandhowaDBMSevaluatesqueriesandcreatesqueryevaluationplans!Fornow,wediscusssimple1-tablequeries.Beforecreatinganindex,mustalsoconsidertheimpactonupdatesintheworkload!Trade-off:Indexescanmakequeriesgofaster,updatesslower(becausealsohavetoupdatetheindexes).Indexesalsorequirediskspace,too.40IndexSelectionGuidelinesAttributesinWHERE
clausearecandidatesforindexkeys.Exactmatchconditionsuggestshashindex.Rangequerysuggeststreeindex.Clusteringisespeciallyusefulforrangequeries;canalsohelponequalityqueriesiftherearemanyduplicates.Multi-attributesearchkeysshouldbeconsideredwhenaWHERE
clausecontainsseveralconditions.Orderofattributesisimportantforrangequeries.Suchindexescansometimesenableindex-onlystrategiesforimportantqueries.Forindex-onlystrategies,clusteringisnotimportant!Trytochooseindexesthatbenefitasmanyqueriesaspossible.Sinceonlyoneindexcanbeclusteredperrelation,chooseitbasedonimportantqueriesthatwouldbenefitthemostfromclustering.41ExamplesofClusteredIndexesB+treeindexonE.agecanbeusedtogetqualifyingrecords.Howselectiveisthecondition?(selectivemeans%ofqualifiedrecords)Isthisindexuseful?ConsidertheGROUPBY
query.IsE.ageindexgood?Whynot?ClusteredE.dnoindexmaybebetter.Equalityqueriesandduplicates:Unclusteringisbadincaseofmanyqualifiedrecords.ClusteringonE.hobbyhelps!SELECTE.dnoFROMEmpEWHEREE.age>40SELECTE.dno,COUNT(*)FROMEmpEWHEREE.age>10GROUPBYE.dnoSELECTE.dnoFROMEmpEWHEREE.hobby=Stamps42CompositeSearchKeysSearchonacombinationoffields.Whichindexcanbeapplied?Equalityquery:Everyfieldvalueisequaltoaconstantvalue.age=12andsal=10Rangequery:Somefieldvalueisnotaconstant.age=13;orsal=10andage>5Theorderoffieldsincompositekeyisimportant!<sal,age>:dataentriesaresortedbysalfirst,thenage.sue1375bobcaljoe121020801112nameagesal<sal,age><age,sal><age><sal>12,2012,1011,8013,7520,1210,1275,1380,111112121310207580DatarecordssortedbynameDataentriesinindexsortedby<sal,age>Dataentriessortedby<sal>Examplesofcompositekeyindexesusinglexicographicorder.43CompositeSearchKeysToretrieveEmprecordswithage=30AND
sal=4000,anindexon<age,sal>wouldbebetterthananindexonageoranindexonsal.Ifconditionis:20<age<30AND3000<sal<5000:Clusteredtreeindexon<age,sal>or<sal,age>.Ifconditionis:age=30AND3000<sal<5000:Clustered<age,sal>indexmuchbetterthan<sal,age>index.Why?For<age,sal>,findthefirstdataentrywith(age=30,sal=3000)andthequalifiedentriesarelikelytobequalified.However,for<sal,age>,findthefirstdataentrywith(sal=3000,age=anything),subsequententriescanhaveanyages.Theorderoffieldsincompositekeyisimportant!Compositeindexesarelarger,updatedmoreoften.44Index-OnlyPlansAnumberofqueriescanbeansweredwitho
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 空气培养模板课件
- 口腔模板课件
- 课前跑步热身课件
- 口腔门诊无菌消毒课件
- 口腔流体介绍课件
- 口腔科普讲课课件
- 考前经验分享课件
- 口腔健康管理课件
- (2026年)医疗核心制度考试及答案
- 口腔护理课件
- 药房员工培训合同协议书2025年版
- 2025中化集团中化资产管理有限公司物业管理高级经理招聘1人(北京)笔试历年难易错考点试卷带答案解析2套试卷
- 合同付款方变更协议书
- 小学德育工作亮点汇报
- 儿童营养包知识培训课件
- 基于“教-学-评”一致性的初中生物单元作业设计
- 土方外运处理协议合同
- GB/T 21121-2024动植物油脂氧化稳定性的测定(加速氧化测试)
- 温泽三坐标测量培训资料
- 岩土工程勘察服务投标方案(技术方案)
- 中药灌肠-1-课件
评论
0/150
提交评论