在Couchbase中编写reduce功能 [英] Writing reduce function in couchbase

查看:76
本文介绍了在Couchbase中编写reduce功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次尝试使用榻榻米.我的json文档看起来像这样:

This is my first attempt at couchbase. My json doc looks like this:

{
   "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.

I want to create a view which tells me all member_ids for a given hash.

类似这样的东西:

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

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

The member_id should appear once in the set.

我写了一个地图函数

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"

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

but I'm not able to move forward from here. How should I change my map function to reduce the result?

推荐答案

地图功能.通常是您的,但会发出meta.id作为值.

Map function. Mostly yours, but emits meta.id as a value.

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 )

Reduce function. Is just return unique array from values (taken from https://stackoverflow.com/a/13486540/98509)

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

这篇关于在Couchbase中编写reduce功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆