在CouchDB中的一个视图中分别求和两个值

时间:2018-11-28 22:19:46

标签: javascript view mapreduce couchdb couchdb-futon

因此,假设我在CouchDB中有以下两个文档:

{
   "_id": "197000000002",
   "_rev": "1-fbe819b01108f30d2e9e96f3fb46eff8",
   "iyear": "1970",
   "region_txt": "North America",
   "country": "130",
   "region": "1",
   "country_txt": "Mexico",
   "nkill": "1",
   "nwound": "1",

}

{
       "_id": "197000000003",
       "_rev": "1-fbe819b01108f30d2e9e96f3fb46eff8",
       "iyear": "1970",
       "region_txt": "North America",
       "country": "130",
       "region": "2",
       "country_txt": "Mexico",
       "nkill": "3",
       "nwound": "1"
    }

我想要的是对所有nkill和nwound值求和,并具有以下内容:

[1970, "Mexico","North America"]    4, 2

此刻,我只能求和两个值之一或将两个值求和,但这不是我想要的。

我的地图函数现在看起来像这样返回结果:

function(doc) {
    if(doc.nkill >= 1) {
        emit([doc.iyear,doc.country_txt,doc.region_txt],parseInt(doc.nkill));
    }
}

我将 _sum 用于reduce函数。

这会给我返回这样的键和值:

[1970, "Mexico", "North America"]   4

1 个答案:

答案 0 :(得分:0)

使用自定义reduce函数代替CouchDB内置的_sum

您可以通过数组或对象作为reduce函数中的值,分别将两个值相加,然后输出新的数组/对象。

为使reduce函数可以使用一个对象(例如),map函数应更改为以下内容:

function(doc) {
    if(doc.nkill >= 1) {
        emit([doc.iyear,doc.country_txt,doc.region_txt],
            {nkill: parseInt(doc.nkill), nwound: parseInt(doc.nwound));
    }
}

一种不同的方式

查看CouchDB文档后,看来the strong preference是要从reduce函数-数组返回标量值。 This SO question涵盖了您的用例:如何从同一查询中分别求和两个不同的值。

相关问题