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?
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.
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).
CouchDB's views are stored in the B-tree file structure.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With