You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@couchdb.apache.org by Apache Wiki <wi...@apache.org> on 2009/04/12 09:14:08 UTC

[Couchdb Wiki] Update of "View Snippets" by WoutMertens

Dear Wiki user,

You have subscribed to a wiki page or wiki category on "Couchdb Wiki" for change notification.

The following page has been changed by WoutMertens:
http://wiki.apache.org/couchdb/View_Snippets

The comment on the change is:
added info about how to get unique results

------------------------------------------------------------------------------
  }}}
  
  In SQL this would be something along the lines of {{{SELECT num_attachments FROM table GROUP BY num_attachments}}} (but this would give extra output for rows containing more than one attachment).
+ 
+ == Generating a list of unique values ==
+ 
+ Here we use the fact that the key for a view result can be an array. Suppose you have a map that generates (key, value) pairs with many duplicates and you want to remove the duplicates. To do so, use ([key, value], null) as the map output.
+ 
+ Call this with ''group=true'' or you only get ''null''.
+ 
+ {{{
+ map: function(doc) {
+   for (var i in doc.links)
+     emit([doc.parent, i], null);
+   }
+ }
+ reduce: function(keys, values) {
+    return null;
+ }
+ }}}
+ 
+ This will give you results like
+ {{{
+ {"rows":[
+ {"key":["thisparent","thatlink"],"value":null},
+ {"key":["thisparent","thatotherlink"],"value":null}
+ ]}
+ }}}
+ 
+ You can then get all the rows for the key "thisparent" with the view parameters ''startkey=["thisparent"]&endkey=["thisparent",{}]&inclusive_end=false''.
+ 
+ Note that the trick here is using the key for what you want to make unique. You can combine this with the counting above to get a count of duplicate values:
+ 
+ {{{
+ map: function(doc) {
+   for (var i in doc.links)
+     emit([doc.parent, i], 1);
+   }
+ }
+ reduce: function(keys, values) {
+    return sum(values);
+ }
+ }}}
  
  == Retrieve the top N tags. ==