Writing contraction functions in couchbase

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" ] } ] } 

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

Something like that:

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

member_id should appear once in the set.

I wrote a display function

 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) } } } 

and it returns

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

but I can't move on from here. How can I change the map function to reduce the result?

+3
source share
1 answer

Card 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) } } } 

Decrease function. Just returns a unique array of values ​​(taken from fooobar.com/questions/60444 / ... )

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

Source: https://habr.com/ru/post/990065/


All Articles