如何使用CouchDB的reduce()函数?

时间:2012-10-12 04:52:40

标签: javascript mapreduce couchdb

我正在尝试聚合CouchDB中的一些数据。数据库中有照片文档,数据库中有评级文档。每个评级文档都是这样的(sans _id和_rev):

{
   "type": "rating",
   "rating": 3 // Integer values are identifiers that map to a string; e.g 1 might mean 'funny'
   "photo": "as9i83ufsafa09uj" // The id of the photo that this rating points to.
}

我想要做的是计算每张照片的每种评级类型。

{
   "key": "as9i83ufsafa09uj", "value": [1, 7, 8, 6] // 1 '0' rating, 7 '1' ratings, etc.
   "key": "photoid2", "value": [3, 0, 0, 8]
}

我正在使用CouchDB视图'MapReduce来实现这种聚合。

"map": "function(doc) {
   if(doc.type == 'rating')
   {
      emit(doc.photo, doc.rating);
   }
}",

"reduce": "function(keys, values, rereduce) {
   var result = new Array(0, 0, 0, 0);

   values.forEach( function(key, value)
   {
      result[value]+=1;
   });

   return result;
}"

地图返回:

{"total_rows":55,"offset":0,"rows":[
{"id":"0aa2c4c9a031eedbcf2795cabc1679be","key":"4aa5ec26-26b8-490a-a9cc-620a0d2136b9","value":0},
{"id":"29f363432e008f5934b4160292e18680","key":"4aa5ec26-26b8-490a-a9cc-620a0d2136b9","value":3},
{"id":"646d0d764623bc2f3ed1354ac03b583e","key":"4aa5ec26-26b8-490a-a9cc-620a0d2136b9","value":2},
...
{"id":"fa5be78402171e3bf1eb1cf91c5fda6e","key":"c63b78b6-ad92-426c-ab64-c9a6ae229b31","value":1}
]}

reduce返回witb group_level = 0:

{"rows":[
{"key":null,"value":[1,1,1,1]}
]}

with group_level = 1:

{"rows":[
{"key":"4aa5ec26-26b8-490a-a9cc-620a0d2136b9","value":[2,2,2,0]},
{"key":"5ad3de4b-d25b-42d3-95e0-df7661becbf3","value":[2,2,2,2]},
{"key":"7600710b-9ae3-4312-876c-ad352722dac3","value":[2,2,2,2]},
{"key":"959f48a2-5018-4938-aab4-086d8824dd75","value":[2,0,0,0]},
{"key":"c63b78b6-ad92-426c-ab64-c9a6ae229b31","value":[2,2,2,2]}
]}

我熟悉MongoDB的map reduce,这个函数可以使用他们的模式。我需要调整什么才能在CouchDB中使用它?

更新 这是对我有用的最终缩减功能。我没有正确地解决rereduce参数。感谢MarcinSkórzewski帮助我更好地理解rereduce。

"reduce": "function(key, values, rereduce) {

        var result = new Array(0, 0, 0, 0);

        if(rereduce == true)
        {
            for(var i = 0; i < values.length; i++)
            {
                var value = values[i];

                for (var j = 0; j < value.length; j++)
                {
                    result[j] += value[j];
                }
            }

            return result;
        }

        for(var i = 0; i < values.length; i++)
        {
            value = values[i];
            result[value]+=1;
        }

        return result;

        }"

1 个答案:

答案 0 :(得分:2)

我认为你没有正确使用rereducevalues元素和返回的数据类型不同。如果只有一个组级别和小型数据(适合单个B树节点),它可以正常工作,因为不必运行rereduce。请查看rereduce的{​​{3}}以及reduce()的{​​{1}}参数的含义。

如果为reduce()发出的值运行map(),则它们是整数,但如果减少先前reduce()获得的值,则它们是数组。您可以使用rereduce,如果它是true添加数组。或者您可以在地图中发出数组(例如,获取[0,0,0,1]而不是3)并始终在reduce()中添加数组,而不必担心rereduce参数。