0
votes

I have following key values emitted in CouchDB view map funtion.

{"key":101,"value":"ABC"}
{"key":101,"value":"ABC"}
{"key":101,"value":"ABC"}
{"key":101,"value":"XYZ"}
{"key":101,"value":"XYZ"}
{"key":101,"value":"XYZ"}
{"key":102,"value":"XYZ"}
{"key":102,"value":"XYZ"}

I need output as unique value count for each key.

{"key":101,"value":2}
{"key":102,"value":1}

How can I go with the reduce function for this?

2
What have you tried? Included your code. What problems did you encounter? - Flimzy

2 Answers

0
votes

If the count of unique values per key is finite and if we can hold them in a Set.

Do the following inside the Reducer :

foreach value for a given key 
iterate each value and add to a set 
emit key, set.size()

Example


Key 101 - Value [ABC, ABC, ABC, XYZ, XYZ, XYZ]
101, create a set s with elements [ABC, XYZ]
emit 101,2 where 2 is s.size()

Key 102 - Value [XYZ, XYZ]
102, create a set s with elements  [XYZ]
emit 102, 1 where 1 is s.size()

Map to emit Key Value as-is. Using an combiner is also recommended.

0
votes

You can try to change your function to something like below and use the _sum reduce function

Assuming that val holds ABC, XYZ and num holds 101, 102

function (doc) {
  if (doc.value) {
    emit([doc.num, doc.val], 1);  
  }
}