Databases Reference
In-Depth Information
Next, you can modify the map function slightly and run the map and reduce functions against the
ratings collection to count the number of each type of rating (1, 2, 3, 4 or 5) for each movie. In
other words, you are counting the collection grouped by rating value for each movie. Here are the
complete map and reduce function defi nitions run against the ratings collection:
> var map = function() {
... emit({ movie_id:this.movie_id, rating:this.rating }, { count:1 });
... };
> var reduce = function(key, values) {
... var count = 0;
... values.forEach(function(v) {
... count += v['count'];
... });
...
... return { count: count };
... };
> var group_by_movies_by_rating = db.ratings.mapReduce(map, reduce);
> db[group_by_movies_by_rating.result].find();
movielens_queries.txt
To get a count of each type of rating for the movie Titanic , identifi ed by movie_id 1721 , you simply
fi lter the MapReduce output using nested property access method like so:
> db[group_by_movies_by_rating.result].find({ “_id.movie_id”:1721 });
{ “_id” : { “movie_id” : 1721, “rating” : 1 }, “value” : { “count” : 100 } }
{ “_id” : { “movie_id” : 1721, “rating” : 2 }, “value” : { “count” : 176 } }
{ “_id” : { “movie_id” : 1721, “rating” : 3 }, “value” : { “count” : 381 } }
{ “_id” : { “movie_id” : 1721, “rating” : 4 }, “value” : { “count” : 500 } }
{ “_id” : { “movie_id” : 1721, “rating” : 5 }, “value” : { “count” : 389 } }
movielens_queries.txt
In the two examples of MapReduce so far, the reduce function is identical but the map function is
different. In each case a count of 1 is established for a different emitted key/value pair. In one a key/
value pair is emitted for each document that has a gender property, whereas in the other a key/value
pair is emitted for each document identifi ed by the combination of a movie id and a rating id.
Next, you could calculate the average rating for each movie in the ratings collection as follows:
> var map = function() {
... emit({ movie_id:this.movie_id }, { rating:this.rating, count:1 });
... };
> var reduce = function(key, values) {
... var sum = 0;
... var count = 0;
... values.forEach(function(v) {
... sum += v['rating'];
... count += v['count'];
... });
Search WWH ::




Custom Search