Database Reference
In-Depth Information
Figure 5-3. Adding Swing to the hierarchy
Now we need to update the ancestor list of the bop document and all its descendants . In order
to do this, we'll first build the subgraph of bop in memory, including all of the descendants of
bop , and then calculate and store the ancestor list for each node in the subgraph.
For the purposes of calculating the ancestor list, we will store the subgraph in a dict contain-
ing all the nodes in the subgraph, keyed by their parent field. This will allow us to quickly
traverse the hierarchy, starting with the bop node and visiting the nodes in order:
from
from collections
collections import
import defaultdict
def
def build_subgraph ( root ):
nodes = db . categories . find (
{ 'ancestors._id' : root [ '_id' ] },
{ 'parent' : 1 , 'name' : 1 , 'slug' : 1 , 'ancestors' : 1 })
nodes_by_parent = defaultdict ( list )
for
for n iin nodes :
nodes_py_parent [ n [ 'parent' ]] . append ( n )
return
return nodes_by_parent
The defaultdict from the Python standard library is a dictionary with a special
behavior when you try to access a key that is not there. In this case, rather than rais-
ing a KeyError like a regular dict , it will generate a new value based on a factory
 
 
Search WWH ::




Custom Search