couchdb-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Joel Reed <joel.r...@visn.biz>
Subject using reduce to get SQL distinct like results
Date Tue, 26 Aug 2008 21:01:56 GMT
I have a bunch of documents that look vaguely like this:

[{ "User":"Jane Doe", "Date":"2008/08/12", } { "User":"Jane Doe", 
"Date":"2008/08/15", }, etc...]

IOW, There might be several entries for each user all with different dates.

I'd like tp combine all "Jane Doe's" records into 1 entry. Some kind of 
output like:

"rows": [ {"key": "Jane Doe", "value": [
{"id":"481bf9e8a0c23bb61eeed4b3707bae59","Date":"2008/08/12"},
{"id":"1e6e541b391efcb9c137d7097e7de6ed","Date":"2008/08/15"}
] } ]


I tried a map/reduce function like this:

"all": {
  "map": "function(doc) { emit(doc.User, doc); }",
  "reduce": "function(keys, values) {
     var tree = {};
     for (var i in keys) 
{                                                            
       var id = keys[i][1];
       var key = values[i].User;
       var value = values[i].Date;

       if (!tree.hasOwnProperty(key)) tree[key] = [];
       var len = tree[key].length;
       tree[key][len] = { id: id, Date: value};
     }

    return tree;
  }

And I get OK output, but not as nice:

"rows":[{"key":null,"value":{"Terri 
Hepburn":[{"id":"481bf9e8a0c23bb61eeed4b3707bae59","Date":"Aug 12, 
2008"},{"id":"1e6e541b391efcb9c137d7097e7de6ed","Date":"Aug 13, 
2008"}],"Portuguese 
Nimrod":[{"id":"5beddf3f80d2662f51a46c3f29dd4e9d","Date":"Aug 20, 
2008"},{"id":"1343194e6dd8e1b07ee1e41949c5a3a3","Date":"Aug 20, 
2008"}],"Paraguayans 
Briana":[{"id":"b0d65454d1395f48a47e4f7b09298a17","Date":"Aug 11, 
2008"},{"id":"af3617bdffd0abfc150e0ebb9b2d6968","Date":"Aug 12, 2008"}],
...

A null key, and everything jammed into the first value. Is that the best 
I can do? Is there a better way to output this from a reduce function? 
Googling has not turned up much for me.

jr


Mime
View raw message