Database Reference
In-Depth Information
def
def
append_post
(
collection
,
dest_userids
,
month
,
post
):
collection
.
update
(
{
'user_id'
: {
'$in'
:
sorted
(
dest_userids
) },
'month'
:
month
},
{
'$push'
: {
'posts'
:
post
} },
multi
=
True
)
In order to quickly update the
social.wall
and
social.news
collections, we once again
need an index on both
user_id
and
month
. This time, however, the ideal order on the indexes
is
month
,
user_id
. This is due to the fact that updates to these collections will always be for
the current month; having month appear first in the index makes the index
right-aligned
, re-
quiring significantly less memory to store the active part of the index.
However, in this case, since we already have an index
user_id
,
month
, which
must
be in that
order to enable sorting on
month
, adding a second index is unnecessary, and would end up
actually using more RAM to maintain two indexes. So even though this particular operation
would benefit from having an index on
month
,
user_id
, it's best to leave out any additional
indexes here.
Maintaining the Social Graph
In a social network, maintaining the social graph is an infrequent but essential operation. To
add a user
other
to the current user
self
's circles, we'll need to run the following function:
def
def
circle_user
(
self
,
other
,
circle
):
circles_path
=
'circles.
%s
.
%s
'
%
(
circle
,
other
[
'_id'
])
db
.
social
.
user
.
update
(
{
'_id'
:
self
[
'_id'
] },
{
'$set'
: {
circles_path
: {
'name'
:
other
[
'name'
]} } })
follower_circles
=
'followers.
%s
.circles'
%
self
[
'_id'
]
follower_name
=
'followers.
%s
.name'
%
self
[
'_id'
]
db
.
social
.
user
.
update
(
{
'_id'
:
other
[
'_id'
] },
{
'$push'
: {
follower_circles
:
circle
},
'$set'
: {
follower_name
:
self
[
'name'
] } })
Note that in this solution, previous posts of the
other
user are not added to the
self
user's
news feed or wall. To actually include these past posts would be an expensive and complex
operation, and goes beyond the scope of this use case.