Database Reference
In-Depth Information
Since the
full_slug
field contains both hierarchical information (via the path) and chrono-
logical information, we can use a simple sort on the
full_slug
field to retrieve a threaded
view:
cursor
=
db
.
comments
.
find
({
'node_id'
:
node_id
})
cursor
=
cursor
.
sort
(
'full_slug'
)
cursor
=
cursor
.
skip
(
page_num
*
page_size
)
cursor
=
cursor
.
limit
(
page_size
)
To support these queries efficiently, maintain two compound indexes on
node_id, posted
and
node_id, full_slug
:
>>>
>>>
db
.
comments
.
ensure_index
([
...
...
(
'node_id'
,
1
), (
'posted'
,
1
)])
>>>
>>>
db
.
comments
.
ensure_index
([
...
...
(
'node_id'
,
1
), (
'full_slug'
,
1
)])
Operation: Retrieve comments via direct links
To directly retrieve a comment, without needing to page through all comments, we can select
by the
slug
field:
comment
=
db
.
comments
.
find_one
({
'node_id'
:
node_id
,
'slug'
:
comment_slug
})
We can also retrieve a “subdiscussion,” or a comment and all of its descendants recursively,
by performing a regular expression prefix query on the
full_slug
field:
import
import
rre
subdiscussion
=
db
.
comments
.
find_one
({
'node_id'
:
node_id
,
'full_slug'
:
re
.
compile
(
'^'
+
re
.
escape
(
parent_full_slug
)) })
subdiscussion
=
subdiscussion
.
sort
(
'full_slug'
)
Since we've already created indexes on
{ node_id: 1, full_slug: 1 }
to support retriev-
ing subdiscussions, we don't need to add any other indexes here to achieve good performance.