hierarchical data_ persistence via closure table _ the b^2 brand.pdf
TRANSCRIPT
-
27/6/2015 HierarchicalData:PersistenceviaClosureTable|TheB^2Brand
http://b2berry.com/2011/11/19/hierarchicaldatapersistenceviaclosuretable/ 1/6
POPULAR LATEST COMMENTS TAGS
HierarchicalData:PersistenceviaClosureTable
NOVEMBER19,2011
HierarchicalData:RenderingwithRazor
NOVEMBER20,2011
ConvertingtheClosureTablefromaWeakEntityAUGUST4,2012
TheVacationStateMachineOCTOBER30,2011
DataWarehousingIISLogsJUNE1,2011
TheB^2Brand
POSTS
Enterkeywords...
HierarchicalData:PersistenceviaClosureTable
NOVEMBER19,2011BYB2BERRY 11COMMENTS
Recently,Ivebeenworkingwithhierarchicaldatausingclosuretables.Theproblemthistechniquesolvesformeispersistinghierarchicalrelationshipsofspecificentitieswithoutanyrestrictiononthesizeofthehierarchyandwhileprovidingasimplewaytoquerythehierarchy.Closuretables,aboveothersolutionslikepathenumeration,maintainreferentialintegrity.
InaseriesofpostsaboutstoringhierarchicaldataImgoingtowalkthroughimplementingasolutionforworkingwithhierarchicaldataatthepersistencelayer,theapplicationlayer,andthepresentationlayer.WellseewhatisnecessarytopersistthehierarchyinSQLServer2008,howwewraptheclosuretablesintheapplication,andhowwebuildhierarchyintheuserinterfacewithMVC3
First,letsdigrightinandlookatwhatsnecessarytosetuptheclosuretable.Intheimagebelowyoullseejustwhatlittleisnecessarytogetgoing.ThetabletitledClosureistheclosuretablewherethemetadataaboutthestructureofthehierarchyisstored.TheParentIDistheforeignkeytotheFamilyMemberIDandtheChildIDistheFamilyMemberIDofoneofthedecedents.ThePathLengthindicateshowfarremovedfromthenodetheChildis.So,ifwearelookingatagrandfather,thenthemselfwouldbePathLength=0,theirchildwouldbePathLength=1,andtheirgrandchildwouldbePathLength=2.
SoftwareEngineer,dataenthusiast,mathliterateandallaroundtechnologynerd
Categories
Data(8)
MVC(2)
ProfessionalDevelopment(2)
Whitepaper(1)
WindowsAzure(1)
Archives
August2012(1)
July2012(1)
December2011(1)
November2011(3)
October2011(1)
July2011(2)
June2011(2)
May2011(2)
TwitterUpdates
Data General MVC ProfessionalDevelopment Whitepaper WindowsAzure
ABOUT.ME BITBL.IT(PODCAST) FEEDBURNER .TUMBLR
-
27/6/2015 HierarchicalData:PersistenceviaClosureTable|TheB^2Brand
http://b2berry.com/2011/11/19/hierarchicaldatapersistenceviaclosuretable/ 2/6
ParentID ChildID PathLength
1 1 0
1 2 1
1 3 1
1 4 2
1 5 1
1 6 2
1 7 2
2 2 0
2 4 1
3 3 0
3 6 1
3 7 1
4 4 0
5 5 0
6 6 0
7 7 0
YoumayhavealsonoticedthattheFamilyMemberstablealsoholdsaParentID.Thismakesthingsconvenient,butisnotcompletelynecessary.TounderstandmoreaboutwhytheParentIDispresent,letslookatthetriggerFamilyMemberClosureTrigger.Everyonescomfortlevelwithdatabasetriggersisdifferentbuttomethisisoneofthoseappropriatecasesforone.Inthiscase,thetriggerisresponsibleforcreatingthemetadataentriesfortheClosuretableeachtimearecordisinsertedintoFamilyMembers(orupdated,deleted,etc).Thisisntabsolutelynecessary,though.Youcoulddefinitelymovethislogicelsewhereanddoawaywiththetriggeraltogether.
Atthispoint,wereallsetupfornewFamilyMemberstobeinsertedintotheFamilyMemberstable.Letstakealookatthedatawhenthesetablesarepopulated.Below,youcanseetheClosureTable(left)andtheFamilyMemberstable.TakeamomenttoobservejustwhattheClosureTableisstoringforus.
12345678910111213141516171819202122232425
Here,wecreatethetriggerwhenanINSERTtakesplaceinFamilyMemberstable.UpdateandDeletearestillnecessarybutleftthemoutforthisdemoCREATETRIGGER[dbo].[FamilyMemberClosureTrigger]ON[dbo].[FamilyMembers]FORINSERTASDECLARE@MemberIDINT;DECLARE@ParentIDINT;GettheFamilyMemberIDofthenewlyinsertedrecordSELECT@MemberID=i.FamilyMemberIDFROMINSERTEDi;GettheIDofthenewrecord'sparentSELECT@ParentID=i.ParentIDFROMINSERTEDi;First,weinserttherecordforthenewlyinsertedFamilyMemberThisisaselfreferencingrecord,meaningtheParentID=ChildIDAndPathLength=0.INSERTINTOClosure(ParentID,ChildID,PathLength)VALUES(@MemberID,@MemberID,0)Next,weinsertmetadataabouthowthisnewfamilymemberisrelatedtotherestofthehierarchy.INSERTINTOClosure(ParentID,ChildID,PathLength)SELECTp.ParentID,c.ChildID,p.PathLength+c.PathLength+1FROMClosurep,[email protected]=@MemberID
Error:Twitterdidnotrespond.Pleasewaitafewminutesandrefreshthispage.
BooksIamReading
ApacheSolr3EnterpriseSearchServerJune
6,2014Enhanceyoursearchwithfacetednavigation,resulthighlighting,relevancyrankedsorting,andmoreComprehensiveinformationonApacheSolr3withexamplesandtipssoyoucanfocusontheimportantpartsIntegrationexampleswithdatabases,webcrawlers,XSLT,Java&embeddedSolr,PHP&Drupal,JavaScript,RubyframeworksAdviceondatamodeling,d[]
EricPugh
TheDataWarehouseToolkit:TheComplete
GuidetoDimensionalModelingFebruary27,
2010Singlemostauthoritativeguidefromtheinventorofthetechnique.Presentsuniquemodelingtechniquesforecommerce,andshowsstrategiesforoptimizingperformance.CompanionWebsiteprovidesupdatesondimensionalmodelingtechniques,linksrelatedtosites,andsourcecodewhereappropriate.
MargyRoss
HeadFirstJava,2ndEditionAugust6,2014
LearningacomplexnewlanguageisnoeasytaskespeciallywhenitsanobjectorientedcomputerprogramminglanguagelikeJava.Youmightthinktheproblemisyourbrain.Itseemstohaveamindofitsown,amindthatdoesn'talwayswanttotakeinthedry,technicalstuffyou'reforcedtostudy.Thefactisyourbraincravesnovelty.It'sc[]
BertBates Follow
Follow The B^2BrandGet every new post deliveredto your Inbox.
Enteryouremailaddress
Signmeup
Build a website with WordPress.com
-
27/6/2015 HierarchicalData:PersistenceviaClosureTable|TheB^2Brand
http://b2berry.com/2011/11/19/hierarchicaldatapersistenceviaclosuretable/ 3/6Data closuretable,data,hierarchy,SQL
FamilyMemberID ParentID Name
1 0 JohnDoe
2 0 BillyDoe
3 1 MaryDoe
4 2 Bobby
5 1 BobbyDoe
6 3 SammyDoe
7 3 MaeDoe
TheClosureTable,bystoringthismetadataabouttheFamilyMembersenablesustodirectlyquerytherelationshipsinthehierarchyprettyquickly.Thatis,wecanaskquestionslikeWhoareallofthegrandchildrenofJohnDoe
Whichresultsin:
ParentID ChildID PathLength
1 4 2
1 6 2
1 7 2
Asyoucansee,thismakesthingsrelativelysimpleforquerying.Though,therearesomedownsidestothissolution.Wecanseethesizeoftheclosuretablewillgrowexponentiallyfasterthantheentitytable(FamilyMembers).Also,theclosuretableisnotsimpletodebug,thatisifthetablebecomescorrupti.e.failedwrites,etc,thenthetablewillneedtoberebuiltasattemptingtotrackdownthebrokenrelationshipvisuallyisnotimpossiblebutanexerciseintedium.Ontheotherhand,therelationshipsareprettysimplesorebuildingpartorallofthehierarchyisntsobad,especiallyifyoualsoimplementtheParentIDontheentitytableitselfitspartofthecharm.
InthenextpostIwillbewalkingthroughhowtobuildacustomdatastructuretoabstracttheapplicationfromtheclosuretableandworkwiththehierarchythroughouttheapplication.
Sharethis:
Twitter 1 Facebook LinkedIn Google
123
SELECT*FROMClosurecWHEREc.ParentID=1ANDPathLength=2
About these ads
Like
Onebloggerlikesthis.
Related
HierarchicalData:ApplyingDataStructures
HierarchicalData:RenderingwithRazor
ScalabilityofReflexiveTransitiveClosureTables
In"Data" In"Data" In"Whitepaper"
-
27/6/2015 HierarchicalData:PersistenceviaClosureTable|TheB^2Brand
http://b2berry.com/2011/11/19/hierarchicaldatapersistenceviaclosuretable/ 4/6
Data closuretable,data,hierarchy,SQL
TheVacationStateMachine HierarchicalData:ApplyingDataStructures
Aboutb2berryViewallpostsbyb2berry
AntoninJanuska(@AntJanus) ReplyAugust3,2012at11:48am
b2berry ReplyAugust3,2012at5:12pm
11ResponsestoHierarchicalData:PersistenceviaClosureTable
Youvegotaprettyamazinganswerthere.Iwonderifyoucouldhelpmewithmydilemma:http://stackoverflow.com/questions/11790108/whattablestructuretousefornesteddata
Itsbasicallyahierarchicalstructureliketheoneyoudescribebutabitmorecomplex.Inyouranalogyofthechildren/parents,letssayIcanmovechildrenaround.
LetssaythatSammyDoe(canmagically)becomeolderthanMayDoeandthusbethefirstgreatgrandchild,howwouldyouhandlethat?Icanimagineaddingapositioncolumntogetthatoutoftheway.
Okaybuthowwouldyou,forexample,callupthe2ndgreatgrandchildofthe1stgrandchildofthe2ndchildofthegrandfather?orhowaboutonlythegrandchildrenofBillyDoewhereonlyMaryDoeistheparent?
Idgreatlyappreciateyourhelp
GreatquestionAntonin,thatdoessoundlikesomeextracomplexity.Haveyouconsideredreorganizingthetree?RecentlyIveusedclosuretablesinanarchitecturewhichallnodesinthetreeareabletoberearrangedandalsoexistinmultipleplacessimultaneously.Thatis,theUIallowsforausertodragsomethinginthehierarchytoacompletelynewlocationinthehierarchy.
Imgoingtoproposetwowaystosolvethis,thefirstwiththeexistingschemaIvepresentedabove,andthesecondsolutionaddsalayerofabstraction.
First:Youcouldhandlethisbyrearrangingtherelationshipsofthenodes.So,ifyoumoveSammyDoeaboveMayDoethenIdgotoworkintheclosuretablechangingparentchildrelationshipsofthetwoinordertoswitchtheirpositions.Ifyouthinkaboutitlikealinkedlist,thelogicissimilarwhereyoullwanttostoretheparentofbothMayDoeandSammyDoesoyoucanmakechangestotherelationshipswithoutloosingalltherelationshipsunderthesenodes,thatisallthechildrenofthesenodesyoureshufflingaround.
Second,andIthinkabettersolutiongivenyourconstraintsistocreateatablewhichabstractbetweenthefamilymembersandthetreeitself.CreateatablecalledFamilyMemberNodeswhichsimplyaliasestheFamilyMemberIDtoapositioninthetree.Then,yourclosuretablewouldbebeconstructedbasedoffyourFamillyMemberNodestable,nottheFamilyMembertableoritskeys.Then,whenyouwanttoswaptwofamilymembersinthetreeyoumakethechangeattheFamilyMemberNodestableandyoudontneedtotouchthestructureofthetreeitself.
Incidentally,itssolutiontwowhichalsoallowsforFamilyMemberstoexistinmultipleplaces(Whichdoesntmakesenseforfamilymemberswhataweirdthought!)butwouldmakesenseforother
-
27/6/2015 HierarchicalData:PersistenceviaClosureTable|TheB^2Brand
http://b2berry.com/2011/11/19/hierarchicaldatapersistenceviaclosuretable/ 5/6
AntoninJanuska(@AntJanus) August3,2012at7:40pm
b2berry August3,2012at10:04pm
AntoninJanuska(@AntJanus) ReplyAugust3,2012at10:40pm
b2berry ReplyAugust4,2012at1:45pm
http://tinyurl.com/satgbiggs06390 ReplyFebruary4,2013at10:10pm
memberswhataweirdthought!)butwouldmakesenseforothercaseslikeashoppingcart,etc.
Anywaylongwindedanswerbutdoesanyofthishelp?
Imthinkingofdoingthesame.HavethatdragndropUIthatallowschangingofthenodes.Butmymainproblemistryingtofigureoutawaytocallupthosespecificnodes(1stoftoplevel,2ndofmid,5thoflast).
ToseeifIunderstandthisright,youreproposing:
*changingaroundtheclosuretablewitheachupdate/changebyupdatingthechild/parentdeclarations.ThisseemsabitcomplexbutIdontseeawayaroundit.*ImnotentirelysureIunderstandyoursecondexplanation.Imtryingtowrapmyheadaroundit.Itwouldbeaninbetweentablewhichwouldholdposition(firstchild,secondchild,firstgrandpa),andtheidwhichcorrespondstotheidinthefamilytable.
Iguessbyimplementingbothofthese,icouldmakeitwork.HavetheNodestabledeclareparent/childrelationships,theinbetweentabledeclareposition,andthemaintablehavetheactualdata.WheneverIwanttochangethepositionofthenode,Icanusetheinbetween.IfIwanttochangetheparent/childrelationship,IllhavetousetheNodestableandupdateitaswellastheinbetweentable.Thanksforyourhelp.Imstillnot100%sureofhowtodothisallefficientlyandifImmissingsomething. especiallyqueryingthisdata.
Thereisasimplersolutionherethanwhatscomingacrosshere,Ithink.Iwillattempttowriteanewpostortwothisweekendwiththedifferentapproachtotheclosuretablewhichshouldmakemysecondsuggestionmoreclear.IvebeenmeaningtorevisitthistopicwithwhatIvelearnedanyway.
Youreawesome.Thankyouforallyourhelp!Illdefinitelybefollowingyourblog
IfoundthisanincrediblyintricatematterbutIfinditextremelyuseful/necessarytowhatImtryingtobuild Itseemslikenooneonredditorstackoverflowhasanygoodideasotherthanbreakingthisdowntoindividualtablesforeachlevel,ditchingthisaltogetherbecauseSQLcantdothis(itobviouslycan),andsomeotherstuff.
Hereyougo!Hopefullythisbetterconveysthe2ndoptionIdescribedabove.Itsnota100%getoutofjailfreecard,butIhadalotofsuccessmodelingwiththisapproachoverthemorevanillaapproachintheabovepost
http://b2berry.com/2012/08/04/convertingtheclosuretablefromaweakentity/
IhavesomemorepostsImaybecrankingoutthisweekendrelativelyminoradditionstotheconcept.
-
27/6/2015 HierarchicalData:PersistenceviaClosureTable|TheB^2Brand
http://b2berry.com/2011/11/19/hierarchicaldatapersistenceviaclosuretable/ 6/6
LeaveaReply
TheB^2Brand. BlogatWordPress.com.TheHeadlinesTheme.
Reply
ExactlywheredidyouacquirethesuggestionstopostHierarchicalData:PersistenceviaClosureTable|TheB^2Brand?IappreciateitAlta
Trackbacks/Pingbacks
1.HierarchicalData:ApplyingDataStructuresTheB^2BrandNovember20,2011[]mypreviouspostIwalkedthroughpersistinghierarchicaldatausingclosuretables.Whileclosuretablesarea[]
2.HierarchicalData:RenderingwithRazorTheB^2BrandNovember20,2011[]walkedthroughpersistinghierarchicaldataviaclosuretablesandthenthroughabstractingtheclosuretableintheapplicationlayer.Now,welllookat[]
3.TheB^2BrandAugust4,2012[]foundtheclosuretableveryusefulincaseswherethereisahighdegreeofinteractionwithhierarchydata.RecentlyI[]
4.ConvertingtheClosureTablefromaWeakEntity|TheB^2BrandAugust4,2012[]foundtheclosuretableveryusefulincaseswherethereisahighdegreeofinteractionwithhierarchydata.RecentlyI[]
Enteryourcommenthere...