Wednesday, 8 April 2009

OMFG I have found my hierarchical model nirvana

Having just given myself a nose bleed by having to think longer than 50 seconds on a single topic I am complete, and that completion has taken the form or using both Nested set and Adjacency List models. To create your basic tree data structure.

Ok if anyone reading this is thinking “nice one Patrick, take some long words string them together and bingo you have your very own buzz word bingo” I’ll expand on this.

When I used to have a tree structure it would be an tidy collection of parent child relationships between nodes. And use this in a Adjacency List model

So…
John would be the dad of Anna and Patrick and Patrick is the dad of Ben
John[A] and has No Parents
Anna[B] has parent of A
Patrick[C] has parent of A
Ben[D] has parent of B and is grandchild of A
John [A]
=Anna[B]
=Patrick[C]
==Ben[D]
So to get From D >> A I need first check Who is the parent of C.
Which is cool a small bit of recursion and we are done.
But………. What if you are going back 15/20 generations. That much recursion is a lot of work for 20 bits of data.
So instead of the extended game of “who is your dad and what does he do?” we also use the nested set Model.

Ok, instead of thinking in terms of nodes and Lines, we treated them as nested containers. Everyone gets a left and right value, every element within that left and right at some level a child. (nose bleed started here).

---A----
-B---C-
--------D

So ABC form a nice little triangle and ACD form a nice line. (the appearance of both patterns are strongly dependant on formatting ;)

With their left and rights, and the step they are on
A 1|8|1
B 2|3|2
C 4|7|2
D 5|6|3
So
1----1A8----
2-2B3--4C7-
3---------5D6

This means I can pull out the ancestral line D by checking to see what other elements have values that contain 5 (D’s left) if when I do this I order the result by the Left descending I can get the Father child relationship in order.

If I want to see to find siblings of C I can take the left and right of the parent A and get all elements that are between 1 and 8 but are on the same step as C (2).

Of course for lots for lots of peeps this is all simple year 1 of the computer science degree, but for me it sparked that little giggling light inside my head that that appears when I realize I can view data from a completely different view point and make that work for me (the last time was “what?!?! you just loop through the structure and process the elements, rather than doing them each individually????

0 comments:

Post a Comment