Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CouchDB View equivalent of SUM & GROUP BY

Tags:

couchdb

I have multiple CouchDB documents representing a timestamp with a property userId and tag (a user can have n timestamps and assign each one a tag). I want to query CouchDB by a specific userId and get a sorted list of tags the user has used (sorted by occurrence).

How would the view look like?

If I want to get a list of all tags sorted by occurrence (no matter from which user) or if I assume that there are only documents with the same userId, I would make it like so:

Map:

function(doc) {
  if(doc.tag) emit(doc.tag, 1); 
}

Reduce:

function(keys, values) {
  return sum(values);
}

But how do I group the result so that I can filter the query by a specific userId?

like image 665
black666 Avatar asked Apr 01 '11 09:04

black666


People also ask

What is view in CouchDB?

It is a simple function definition. You provide CouchDB with view functions as strings stored inside the views field of a design document. You don't run it yourself. Instead, when you query your view, CouchDB takes the source code and runs it for you on every document in the database your view was defined in.

How do I check my CouchDB data?

Try this URL: http://localhost:5984/_utils/, it will open FUTON editor. Show activity on this post. CouchDB is a NOSQL database. So it works using HTTP requests (url based).

Where does the permanent views are stored in CouchDB?

CouchDB's views are stored in the B-tree file structure.


1 Answers

Answering my own question.

Seems like CouchDB supports arrays as keys. With that in mind it's pretty simple:

Map:

function(doc) {
  if(doc.tag) emit([doc.userId, doc.tag], 1); 
}

Reduce:

function(keys, values) {
  return sum(values);
}

The result is then sorted by userId & tag.

like image 165
black666 Avatar answered Sep 19 '22 01:09

black666