写入减少在couchbase中的功能

时间:2013-04-23 19:52:48

标签: mapreduce couchbase

这是我在沙发基地的第一次尝试。我的json doc看起来像这样:

{
   "member_id": "12345",
   "devices": [
       {
           "device_id": "1",
           "hashes": [
               "h1",
               "h2",
               "h3",
               "h4"
           ]
       },
       {
           "device_id": "2",
           "hashes": [
               "h1",
               "h2",
               "h3",
               "h4",
               "h5",
               "h6",
               "h7"
           ]
       }
   ]
}

我想创建一个视图,告诉我给定哈希的所有member_id。

这样的事情:

h1["12345","233","2323"]  //233,2323 are other member id    
h2["12345"]

member_id应该在集合中出现一次。

我写了一个地图功能

function (doc, meta) {
  for(i=0;i< doc.devices.length;i++)
  {
    for(j=0;j< doc.devices[i].hashes.length;j++)  {
        emit(doc.devices[i].hashes[j],null)
          }
  }
}

然后返回

h1 "12345"
h1 "12345"
h2 "12345"
h1 "233"

但是我无法从这里前进。我该如何更改地图功能以减少结果?

1 个答案:

答案 0 :(得分:5)

地图功能。主要是你的,但作为一个值发出meta.id

function(doc, meta) {
  for(i=0; i< doc.devices.length; i++) {
    for(j=0; j< doc.devices[i].hashes.length; j++)  {
      emit(doc.devices[i].hashes[j], meta.id)
    }
  }
}

减少功能。只是从值(取自https://stackoverflow.com/a/13486540/98509

返回唯一数组
function(keys, values, rereduce) {
  return values.filter(function (e, i, arr) {
    return arr.lastIndexOf(e) === i;
  });
}