在couchbase中编写reduce函数



这是我第一次尝试使用couchbase。我的json文档是这样的:

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

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

像这样:

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

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

我写了一个map函数

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"

但我无法从这里继续前进。我应该如何改变我的地图功能,以减少结果?

地图功能。主要是你的,但是输出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)
    }
  }
}

Reduce函数。只是从值返回唯一数组(取自https://stackoverflow.com/a/13486540/98509)

function(keys, values, rereduce) {
  return values.filter(function (e, i, arr) {
    return arr.lastIndexOf(e) === i;
  });
}

最新更新