2013-04-23 53 views
3

这是我第一次尝试在couchbase上。我的JSON文档看起来是这样的:在couchbase中编写减少功能

{ 
    "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应该在集合中出现一次。

我写了一个地图功能

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" 

,但我不能够从这里向前迈进。我应该如何改变我的地图功能以减少结果?

回答

3

地图功能。大多数是你的,但发出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; 
    }); 
} 
+0

thnx它的工作原理! – harshit 2013-04-24 21:50:48