Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing user ratings / favorites on CouchDB

I'm considering using CouchDB for an upcoming site, but I'm a little confused as far as far as how to implement a system of user ratings for the site. Basically, each item of content can be rated by a given user. What way of doing this makes the most sense in the CouchDB model? I would think the DRYest and most logical way would be to have 3 different document types, Content, Users, and a user_rating doc that looks something like this.

{
  user_id: "USERID"
  content_id: "CONTENTID"
  rating: 6
}

Then, I'd create a view where the map was the set of all content docs and user_rating docs keyed by content doc ids, and where the reduce tallied the mean of the ratings and returned the content doc keyed by content doc id.

Is that the best way of doing this? I haven't yet found much in the way of resources on CouchDB best practices so I'm pretty unsure of all this stuff.

My Conclusion: The accepted answer below, which is what I pretty much was going to implement does work, but beware, the docs need to be keyed by content doc id which makes advanced queries based on other document properties troublesome. I'm going back to SQL for my needs in this app.

like image 220
Andrew Cholakian Avatar asked Jan 23 '23 21:01

Andrew Cholakian


1 Answers

Sounds like you've got a reasonable idea going. CouchDB is so new that I think it'll take awhile for best practices to shake out.

A map/reduce pair like this might form a reasonable starting point.

map:

function(doc) {
   if(doc.type='rating' && doc.content_id) {
     emit(doc.content_id, doc.rating);
   }
}

reduce:

function(keys, values) {
   return sum(values)/values.length
}

NB: That map function requires adding the proper type to your Rating model:

{
  type: 'rating',
  user_id: "USERID",
  content_id: "CONTENTID",
  rating: 6
}
like image 178
Hank Avatar answered Jan 26 '23 09:01

Hank