Database Reference
In-Depth Information
At a minimum, you'll want indexes on the thread_id and path fields, as you'll always
be querying on exactly one of these fields:
db.comments.ensureIndex({thread_id: 1})
db.comments.ensureIndex({path: 1})
Now the question is how you go about querying and displaying the tree. One of the
advantages of the materialized path pattern is that you query the database only once,
whether you're displaying the entire comment thread or just a sub-tree within the
thread. The query for the first of these is straightforward:
db.comments.find({thread_id: ObjectId("4d692b5d59e212384d95223a")})
The query for a particular sub-tree is more subtle because it uses a prefix query:
db.comments.find({path: /^4d692b5d59e212384d95001/})
This returns all comments with a path beginning with the specified string. This string
represents the _id of the comment with the username plotinus , and if you examine
the path field on each child comment, it's easy to see that they'll all satisfy the query.
And they'll do so quickly because these prefix queries can use the index on path .
Getting the list of comments is easy, since it requires just one database query. Dis-
playing them is trickier because you need a list that preserves thread order. This
requires a bit of client-side processing, which you can achieve with the following Ruby
methods. 2 The first method, threaded_list , builds a list of all root-level comments
and a map that keys parent ID s to lists of child nodes:
def threaded_list(cursor, opts={})
list = []
child_map = {}
start_depth = opts[:start_depth] || 0
cursor.each do |comment|
if comment['depth'] == start_depth
list.push(comment)
else
matches = comment['path'].match(/([d|w]+)$/)
immediate_parent_id = matches[1]
if immediate_parent_id
child_map[immediate_parent_id] ||= []
child_map[immediate_parent_id] << comment
end
end
end
assemble(list, child_map)
end
The assemble method takes the list of root nodes and the child map and then builds
a new list in display order:
2
This topic's source code includes a complete example of threaded comments with materialized paths using
the display methods presented here.
Search WWH ::




Custom Search