You are on page 1of 6

27/6/2015

HierarchicalData:PersistenceviaClosureTable|TheB^2Brand

TheB^2Brand
ABOUT.ME

Data

BITBL.IT(PODCAST)

General

MVC

FEEDBURNER

.TUMBLR

ProfessionalDevelopment

POSTS

Whitepaper

WindowsAzure

Enterkeywords...

SoftwareEngineer,dataenthusiast,

HierarchicalData:Persistencevia
ClosureTable
NOVEMBER19,2011BYB2BERRY

11COMMENTS

mathliterateandallaround
technologynerd

POPULAR

LATEST

COMMENTS

TAGS

HierarchicalData:Persistence
viaClosureTable
NOVEMBER19,2011

HierarchicalData:Rendering
withRazor
NOVEMBER20,2011

ConvertingtheClosureTable
fromaWeakEntity
AUGUST4,2012

TheVacationStateMachine
OCTOBER30,2011

DataWarehousingIISLogs
JUNE1,2011

Recently,Ivebeenworkingwithhierarchicaldatausingclosuretables.Theproblemthis
techniquesolvesformeispersistinghierarchicalrelationshipsofspecificentitieswithoutany
restrictiononthesizeofthehierarchyandwhileprovidingasimplewaytoquerythehierarchy.
Closuretables,aboveothersolutionslikepathenumeration,maintainreferentialintegrity.
InaseriesofpostsaboutstoringhierarchicaldataImgoingtowalkthroughimplementinga
solutionforworkingwithhierarchicaldataatthepersistencelayer,theapplicationlayer,andthe
presentationlayer.WellseewhatisnecessarytopersistthehierarchyinSQLServer2008,
howwewraptheclosuretablesintheapplication,andhowwebuildhierarchyintheuser
interfacewithMVC3
First,letsdigrightinandlookatwhatsnecessarytosetuptheclosuretable.Intheimage
belowyoullseejustwhatlittleisnecessarytogetgoing.ThetabletitledClosureistheclosure
tablewherethemetadataaboutthestructureofthehierarchyisstored.TheParentIDisthe
foreignkeytotheFamilyMemberIDandtheChildIDistheFamilyMemberIDofoneof
thedecedents.ThePathLengthindicateshowfarremovedfromthenodetheChildis.So,if
wearelookingatagrandfather,thenthemselfwouldbePathLength=0,theirchildwouldbe
PathLength=1,andtheirgrandchildwouldbePathLength=2.

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

http://b2berry.com/2011/11/19/hierarchicaldatapersistenceviaclosuretable/

1/6

27/6/2015

HierarchicalData:PersistenceviaClosureTable|TheB^2Brand
Error:Twitterdidnotrespond.Pleasewaitafew
minutesandrefreshthispage.

BooksIamReading
ApacheSolr3EnterpriseSearchServerJune
6,2014
Enhanceyoursearchwithfaceted

YoumayhavealsonoticedthattheFamilyMemberstablealsoholdsaParentID.Thismakes
thingsconvenient,butisnotcompletelynecessary.Tounderstandmoreaboutwhythe
ParentIDispresent,letslookatthetriggerFamilyMemberClosureTrigger.Everyonescomfort
levelwithdatabasetriggersisdifferentbuttomethisisoneofthoseappropriatecasesforone.
Inthiscase,thetriggerisresponsibleforcreatingthemetadataentriesfortheClosuretable
eachtimearecordisinsertedintoFamilyMembers(orupdated,deleted,etc).Thisisnt
absolutelynecessary,though.Youcoulddefinitelymovethislogicelsewhereanddoawaywith
thetriggeraltogether.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

Here,wecreatethetriggerwhenanINSERTtakesplaceinFamilyMemberstable.
UpdateandDeletearestillnecessarybutleftthemoutforthisdemo
CREATETRIGGER[dbo].[FamilyMemberClosureTrigger]ON[dbo].[FamilyMembers]
FORINSERT
AS
DECLARE@MemberIDINT;
DECLARE@ParentIDINT;

GettheFamilyMemberIDofthenewlyinsertedrecord
SELECT@MemberID=i.FamilyMemberIDFROMINSERTEDi;
GettheIDofthenewrecord'sparent
SELECT@ParentID=i.ParentIDFROMINSERTEDi;

First,weinserttherecordforthenewlyinsertedFamilyMember
Thisisaselfreferencingrecord,meaningtheParentID=ChildID
AndPathLength=0.
INSERTINTOClosure(ParentID,ChildID,PathLength)
VALUES(@MemberID,@MemberID,0)
Next,weinsertmetadataabouthowthisnewfamilymember
isrelatedtotherestofthehierarchy.
INSERTINTOClosure(ParentID,ChildID,PathLength)
SELECTp.ParentID,c.ChildID,p.PathLength+c.PathLength+1
FROMClosurep,Closurec
WHEREp.ChildID=@ParentId
ANDc.ChildID=@MemberID

navigation,resulthighlighting,relevancy
rankedsorting,andmore
ComprehensiveinformationonApache
Solr3withexamplesandtipssoyoucan
focusontheimportantpartsIntegration
exampleswithdatabases,webcrawlers,
XSLT,Java&embeddedSolr,PHP&
Drupal,JavaScript,Ruby
frameworksAdviceondatamodeling,d
[]
EricPugh
TheDataWarehouseToolkit:TheComplete
GuidetoDimensionalModelingFebruary27,
2010
Singlemostauthoritativeguidefromthe
inventorofthetechnique.Presents
uniquemodelingtechniquesfore
commerce,andshowsstrategiesfor
optimizingperformance.Companion
Websiteprovidesupdateson
dimensionalmodelingtechniques,links
relatedtosites,andsourcecodewhere
appropriate.
MargyRoss
HeadFirstJava,2ndEditionAugust6,2014
Learningacomplexnewlanguageisno
easytaskespeciallywhenitsanobject

Atthispoint,wereallsetupfornewFamilyMemberstobeinsertedintotheFamilyMembers
table.Letstakealookatthedatawhenthesetablesarepopulated.Below,youcanseethe
ClosureTable(left)andtheFamilyMemberstable.Takeamomenttoobservejustwhatthe
ClosureTableisstoringforus.

orientedcomputerprogramming
languagelikeJava.Youmightthinkthe
problemisyourbrain.Itseemstohavea
mindofitsown,amindthatdoesn't
alwayswanttotakeinthedry,technical

ParentID

ChildID

PathLength

stuffyou'reforcedtostudy.Thefactis
yourbraincravesnovelty.It'sc[]

Follow The B^2


Brand 1

2
Signmeup
0

Build a website 1with WordPress.com

Follow

BertBates

2 post delivered
Get every new
to your Inbox.
1
Enteryouremailaddress
2

http://b2berry.com/2011/11/19/hierarchicaldatapersistenceviaclosuretable/

2/6

27/6/2015

HierarchicalData:PersistenceviaClosureTable|TheB^2Brand

FamilyMemberID

ParentID

Name

JohnDoe

BillyDoe

MaryDoe

Bobby

BobbyDoe

SammyDoe

MaeDoe

TheClosureTable,bystoringthismetadataabouttheFamilyMembersenablesustodirectly
querytherelationshipsinthehierarchyprettyquickly.Thatis,wecanaskquestionslikeWho
areallofthegrandchildrenofJohnDoe
1
2
3

SELECT*FROMClosurec
WHEREc.ParentID=1
ANDPathLength=2

Whichresultsin:
ParentID

ChildID

PathLength

Asyoucansee,thismakesthingsrelativelysimpleforquerying.Though,therearesome
downsidestothissolution.Wecanseethesizeoftheclosuretablewillgrowexponentiallyfaster
thantheentitytable(FamilyMembers).Also,theclosuretableisnotsimpletodebug,thatisif
thetablebecomescorrupti.e.failedwrites,etc,thenthetablewillneedtoberebuiltas
attemptingtotrackdownthebrokenrelationshipvisuallyisnotimpossiblebutanexercisein
tedium.Ontheotherhand,therelationshipsareprettysimplesorebuildingpartorallofthe
hierarchyisntsobad,especiallyifyoualsoimplementtheParentIDontheentitytableitselfits
partofthecharm.
InthenextpostIwillbewalkingthroughhowtobuildacustomdatastructuretoabstractthe
applicationfromtheclosuretableandworkwiththehierarchythroughouttheapplication.
About these ads

Sharethis:

Twitter

Facebook

LinkedIn

Google

Like
Onebloggerlikesthis.

Related

HierarchicalData:Applying
DataStructures
In"Data"

Data

HierarchicalData:
RenderingwithRazor
In"Data"

ScalabilityofReflexive
TransitiveClosureTables
In"Whitepaper"

closuretable,data,hierarchy,SQL

http://b2berry.com/2011/11/19/hierarchicaldatapersistenceviaclosuretable/

3/6

27/6/2015

HierarchicalData:PersistenceviaClosureTable|TheB^2Brand
Data

closuretable,data,hierarchy,SQL

Aboutb2berry
Viewallpostsbyb2berry

TheVacationStateMachine

HierarchicalData:ApplyingDataStructures

11ResponsestoHierarchicalData:PersistenceviaClosureTable
AntoninJanuska(@AntJanus)

August3,2012at11:48am

Reply

Youvegotaprettyamazinganswerthere.Iwonderifyoucouldhelpme
withmydilemma:http://stackoverflow.com/questions/11790108/what
tablestructuretousefornesteddata
Itsbasicallyahierarchicalstructureliketheoneyoudescribebutabit
morecomplex.Inyouranalogyofthechildren/parents,letssayIcan
movechildrenaround.
LetssaythatSammyDoe(canmagically)becomeolderthanMayDoe
andthusbethefirstgreatgrandchild,howwouldyouhandlethat?Ican
imagineaddingapositioncolumntogetthatoutoftheway.
Okaybuthowwouldyou,forexample,callupthe2ndgreatgrandchildof
the1stgrandchildofthe2ndchildofthegrandfather?orhowaboutonly
thegrandchildrenofBillyDoewhereonlyMaryDoeistheparent?
Idgreatlyappreciateyourhelp

b2berry

August3,2012at5:12pm

Reply

GreatquestionAntonin,thatdoessoundlikesomeextracomplexity.
Haveyouconsideredreorganizingthetree?RecentlyIveused
closuretablesinanarchitecturewhichallnodesinthetreeareable
toberearrangedandalsoexistinmultipleplacessimultaneously.
Thatis,theUIallowsforausertodragsomethinginthehierarchyto
acompletelynewlocationinthehierarchy.
Imgoingtoproposetwowaystosolvethis,thefirstwiththeexisting
schemaIvepresentedabove,andthesecondsolutionaddsalayer
ofabstraction.
First:
Youcouldhandlethisbyrearrangingtherelationshipsofthenodes.
So,ifyoumoveSammyDoeaboveMayDoethenIdgotoworkin
theclosuretablechangingparentchildrelationshipsofthetwoin
ordertoswitchtheirpositions.Ifyouthinkaboutitlikealinkedlist,
thelogicissimilarwhereyoullwanttostoretheparentofbothMay
DoeandSammyDoesoyoucanmakechangestotherelationships
withoutloosingalltherelationshipsunderthesenodes,thatisallthe
childrenofthesenodesyoureshufflingaround.
Second,andIthinkabettersolutiongivenyourconstraintsisto
createatablewhichabstractbetweenthefamilymembersandthe
treeitself.CreateatablecalledFamilyMemberNodeswhichsimply
aliasestheFamilyMemberIDtoapositioninthetree.Then,your
closuretablewouldbebeconstructedbasedoffyour
FamillyMemberNodestable,nottheFamilyMembertableoritskeys.
Then,whenyouwanttoswaptwofamilymembersinthetreeyou
makethechangeattheFamilyMemberNodestableandyoudont
needtotouchthestructureofthetreeitself.
Incidentally,itssolutiontwowhichalsoallowsforFamilyMembersto
existinmultipleplaces(Whichdoesntmakesenseforfamily
memberswhataweirdthought!)butwouldmakesenseforother

http://b2berry.com/2011/11/19/hierarchicaldatapersistenceviaclosuretable/

4/6

27/6/2015

HierarchicalData:PersistenceviaClosureTable|TheB^2Brand
memberswhataweirdthought!)butwouldmakesenseforother
caseslikeashoppingcart,etc.
Anywaylongwindedanswerbutdoesanyofthishelp?

AntoninJanuska(@AntJanus)

August3,2012at7:40pm

Imthinkingofdoingthesame.HavethatdragndropUIthat
allowschangingofthenodes.Butmymainproblemistryingto
figureoutawaytocallupthosespecificnodes(1stoftoplevel,
2ndofmid,5thoflast).
ToseeifIunderstandthisright,youreproposing:
*changingaroundtheclosuretablewitheachupdate/changeby
updatingthechild/parentdeclarations.Thisseemsabitcomplex
butIdontseeawayaroundit.
*ImnotentirelysureIunderstandyoursecondexplanation.Im
tryingtowrapmyheadaroundit.Itwouldbeaninbetweentable
whichwouldholdposition(firstchild,secondchild,firstgrandpa),
andtheidwhichcorrespondstotheidinthefamilytable.
Iguessbyimplementingbothofthese,icouldmakeitwork.
HavetheNodestabledeclareparent/childrelationships,thein
betweentabledeclareposition,andthemaintablehavethe
actualdata.WheneverIwanttochangethepositionofthenode,
Icanusetheinbetween.IfIwanttochangetheparent/child
relationship,IllhavetousetheNodestableandupdateitaswell
astheinbetweentable.
Thanksforyourhelp.Imstillnot100%sureofhowtodothisall
efficientlyandifImmissingsomething. especiallyquerying
thisdata.

b2berry

August3,2012at10:04pm

Thereisasimplersolutionherethanwhatscomingacrosshere,
Ithink.Iwillattempttowriteanewpostortwothisweekendwith
thedifferentapproachtotheclosuretablewhichshouldmakemy
secondsuggestionmoreclear.Ivebeenmeaningtorevisitthis
topicwithwhatIvelearnedanyway.

AntoninJanuska(@AntJanus)

August3,2012at10:40pm

Reply

Youreawesome.Thankyouforallyourhelp!Illdefinitelybefollowing
yourblog
IfoundthisanincrediblyintricatematterbutIfinditextremely
useful/necessarytowhatImtryingtobuild Itseemslikenooneon
redditorstackoverflowhasanygoodideasotherthanbreakingthisdown
toindividualtablesforeachlevel,ditchingthisaltogetherbecauseSQL
cantdothis(itobviouslycan),andsomeotherstuff.

b2berry

August4,2012at1:45pm

Reply

Hereyougo!Hopefullythisbetterconveysthe2ndoptionIdescribed
above.Itsnota100%getoutofjailfreecard,butIhadalotof
successmodelingwiththisapproachoverthemorevanillaapproach
intheabovepost
http://b2berry.com/2012/08/04/convertingtheclosuretablefroma
weakentity/
IhavesomemorepostsImaybecrankingoutthisweekend
relativelyminoradditionstotheconcept.

http://tinyurl.com/satgbiggs06390

February4,2013at10:10pm

http://b2berry.com/2011/11/19/hierarchicaldatapersistenceviaclosuretable/

Reply

5/6

27/6/2015

HierarchicalData:PersistenceviaClosureTable|TheB^2Brand
Reply

ExactlywheredidyouacquirethesuggestionstopostHierarchical
Data:PersistenceviaClosure
Table|TheB^2Brand?IappreciateitAlta

Trackbacks/Pingbacks
1. HierarchicalData:ApplyingDataStructuresTheB^2BrandNovember20,2011
[]mypreviouspostIwalkedthroughpersistinghierarchicaldatausingclosuretables.Whileclosure
tablesarea[]
2. HierarchicalData:RenderingwithRazorTheB^2BrandNovember20,2011
[]walkedthroughpersistinghierarchicaldataviaclosuretablesandthenthroughabstractingthe
closuretableintheapplicationlayer.Now,welllookat[]
3. TheB^2BrandAugust4,2012
[]foundtheclosuretableveryusefulincaseswherethereisahighdegreeofinteractionwithhierarchy
data.RecentlyI[]
4. ConvertingtheClosureTablefromaWeakEntity|TheB^2BrandAugust4,2012
[]foundtheclosuretableveryusefulincaseswherethereisahighdegreeofinteractionwithhierarchy
data.RecentlyI[]

LeaveaReply
Enteryourcommenthere...

TheB^2Brand.

http://b2berry.com/2011/11/19/hierarchicaldatapersistenceviaclosuretable/

BlogatWordPress.com.TheHeadlinesTheme.

6/6

You might also like