Nested Sets
Nested Sets provide a fantastic way of traversing hierarchical data. Once processed, they are able to very rapidly walk large data trees.
Suppose you're given a list of products and are asked:
"What products does the clothing category contain?"
"What products are my siblings?"
"Do I have any products under my category?"
All of these questions are easily answered by processing the list of items into a Nested Set. Once the conversion process is finished, it's very easy to query the set and it's incredibly fast.
Example - Products
Class used in this example
The sample class is here
SDK
Converting the list
To convert a list of items to a nested set, simply create a new NestedSet
by supplying the Root
, ID
, and Parent
fields.
Once finished, this gives you access to all of the other query abilities
Upline
Upline is how you traverse a tree upwards. So starting from key 15(vegetables), let's walk all the way back to "All Products".
Downline
Downline is how you traverse a tree downwards. So starting from key 1(electronic), let's walk all the way down.
Siblings
Siblings is how you traverse a tree sideways. So starting from key 14(pizza), let's see what other siblings we have.
The Nested Set Node
Every item is converted by creating a new NestedSet<T>
class, where the generic parameter is the type of objects that were originally processed. This class provides several additional properties available for use, as well as access to the original class used to convert.
Here's an example of retrieving the root node (key 0).
Let's look at some of the properties of this NestedSet<
Product
>
below.
ID / ParentID
These properties are assigned from the lookup. They are the ID and Parent fields from the supplied class
HLevel
This property is the horizontal level in the tree, starting from 1(root) to n(lowest level)
Left / Right
These properties are the left and right identifiers for where the node is located in the tree
NodeNumber
A numbered index starting from 1, moving down and across the tree
NodeCount
How many nodes does this node contain in it's downline, including itself.
Node
The original class, in our example, this is a Product
.
Last updated