Ordering emitted results by 'popularity'
Im currently using couchdb for info on users. Users can have friends on 开发者_如何转开发my site. I would like to display all the people that have added 'Me' as friend ordered by the amount of people that have 'some_user' as friend
A simplified document would look like this
{
"_id": "some_id",
"Name": "Some user",
"lastMod": "1316300162",
"aFriends": [
{
"Name": Me",
"More": "More info ... "
},
{
"Name": Friend1"
"More": "More info ... "
}
]
}
I currently use this view to show all friends
function(doc) {
if(doc.aFriends.length > 0) {
for(var i in doc.aFriends) {
emit(doc.aFriends[i]['Name'],{UserName: doc.Name, More: doc.aFriends[i]['More']});
}
}
}
However this just shows the Names in alphabetic order. I would like to order them by the amount of Users that have the emitted user as friend. Is there any good way to index this in couchdb ?
Floor
You can't do this directly in CouchDB because you can only operate on one document at a time.
To run this sort of query you need to denormalize the popularity of a user into their document and sort based on that. This is a bit complicated as you need to ensure that you keep the value updated as a user's friends change.
You have a few options on how to do this, but which is best depends on how your code is structured.
You could redenormalize the value for all of a user's friends as part of the save function for the User object. This has the advantage of being simple and instantly updating the value, but it will slow down the save and if you save Users in several places will be complicated.
You could use a background task processing system (like Celery) to update the value. This is similar to updating it as part of the save function, but you trade off the instant update against a faster save process.
Lastly you could monitor _changes to watch for changes in friend lists and denormalizing the value there. This has the advantage of keeping the update in a single place and entirely separate to the rest of your code, as well as guaranteeing that you won't miss and update.
精彩评论