Based on what I see here, (I'll change my answer if needed) key1
and key2
look like independent fields, so you'll need 2 separate views.
I created 5 simple documents in my test database:
// I've left out fields like _id and _rev for the sake of simplicity
{ "key1": "somevalue" }
{ "key1": "somevalue" }
{ "key2": "anotherval" }
{ "key2": "andanother" }
{ "key2": "andanother" }
Here are the 2 view queries you'll need:
// view for key1
function(doc) {
if (doc.key1) {
emit("key1", doc.key1);
}
}
// view for key2
function(doc) {
if (doc.key2) {
emit("key2", doc.key2);
}
}
From there, your reduce function can return all the values in an array by just doing this:
function (key, values) {
return values;
}
However, you specifically mentioned distinct values. Since JavaScript doesn't have a native unique()
method for arrays, and we can't use CommonJS modules in view functions, we'll have to add our own logic for that. I just copy-pasted the first array.unique()
function I found on Google, you can write your own that is better optimized for sure.
function (key, values, rereduce) {
var o = {}, i, l = values.length, r = [];
for (i = 0; i < l; i += 1) {
o[values[i]] = values[i];
}
for (i in o) {
r.push(o[i]);
}
return r;
}
You'll use this same reduce function in both views. When you query any of those views, by default it will also perform the reduce. (You'll need to explicitly pass reduce=false
to get just the results of your map
function.
Here are the result-sets you'd retrieve using the above map/reduce
queries: (remember they are 2 separate queries)
{"rows":[
{"key":"key1", "value": ["somevalue"]}
]}
{"rows":[
{"key": "key2", "value": ["anotherval", "andanother"]}
]}
key1
andkey2
completely different fields altogether? Are they somehow related? – Dalliance