Grouping using Map and Reduce - couchdb

I have some documents with a "status" field of "Green", "Red", "Amber".
I'm sure it's possible to use MapReduce to produce a grouped response containing three keys (one for each status), each with a value containing an array of all the documents with that key. However, I'm struggling on how to use re(reduce) functions.
Map function:
function(doc) {
emit(doc.status, doc);
}
Reduce function: ???

This is not a problem that reduce is intended to solve; reduce in CouchDB is for aggregation.
If I understand you correctly, you want this;
Map:
function(doc) {
for (var i in doc.status) {
emit(doc.status[i], null);
}
}
You can then find all docs of status Green with;
/_design/foo/_view/bar?key="Green"&include_docs=true
This will return a list of all docs with that status. If you wish to find docs of more than one status in a single query, then use http POST with a body of this form;
{"keys":["Green", "Red"]}
HTH,
B.

Generally speaking, you will not use a reduce function to obtain your list of documents. A reduce is meant to take a list, and reduce it to a single value. In fact, there is an upper limit to the size of a reduce value anyways, and using entire documents will trigger a reduce_overflow error. Examples of reduces are counts, sums, averages, etc. Stick with the map query, and you will have your values collated and sorted by the status value.
On another, possibly unrelated note, I would not emit the document with your view. You can just use the include_docs view query parameter, and achieve the same effect, while saving disk-space in the process. The trade-off is that internally the doc will have to be retrieved one-by-one. (but since they're indexed already by _id anyways, it's usually a negligible difference.

Related

Get an object in collection by object index

I have a collection of objects
[{name: Peter}, {name: Evan}, {name: Michael}];
I and i want to get an object for example {name: Evan} by his index(1).
How can i pull this out?
I tried get All objects by find() and then get an object with index but it's not a good idea in terms of speed.
There are a few notable aspects of this question. In the comments you clarify:
yes they are different documents. By the index I mean const users = await User.find(); users[1] // {name: "Evan"}
Probably what you are looking to do here is something along the lines of:
const users = await User.find().skip(1).limit(1);
This will return a cursor that will contain just the single document that you are looking for.
Keep in mind, however, that the without providing a sort to the operation the database is free to return the results in any order. So the "index" (position) is not guaranteed to be consistent without the sort clause.
I tried get All objects by find() and then get an object with index but it's not a good idea in terms of speed.
In general, your current approach requires that the database iterate through all of the items being skipped which can be slow. Limiting the results at least reduces the amount of network activity that is required. Depending on what you are trying to achieve, you could consider setting a smaller batch size (and iterating the cursor) or using range queries as outlined on that page.

Couchdb how to map reduce

This is my sample JSON structure stored in couchdb:
[{"_id":"567567983d6229ccf572c1a2fcad2fbd6","_rev":"1-8666754b35b18c92f005bb64d9c04712a5f","startTime":1467985647,"uuid":"216743afa424dfsf","from":"IN","to":"NG","duration":"121"},{"_id":"4774f983d6229ccf572c1a2fcad2fbd6","_rev":"1-8e9fb35b18c92f005bb64d9c04712a5f","startTime":1467983347,"uuid":"2134jl13k4j343l243","from":"US","to":"DE","duration":"210"}]
Using reduce function can we produce an output like:
{
outgoing : {US:1, IN:1}, inbound: {NG:1, DE:1}, duration:331
}
I would not use a reduce function for this. The view documentation says:
If you don’t reduce your values to a single scalar value or a small fixed-sized object or array with a fixed number of scalar values of small sizes, you are probably doing it wrong.
Instead, you could use a list function, which allows you to transform the rows of a given view result in any way you like.
I found this guide helpful: Rendering Content Based-On Multiple Documents with List Functions

couchDB reduce: does rereduce preserve the order of results from map?

With a couchdb view, we get results ordered by key. I have been using this to get values associated with a highest number. For example, take this result (in key: value form):
{1:'sam'}
{2:'jim'}
{4:'joan'}
{5:'jill'}
couchDB will sort those according to the key. (It could be helpful to think of the key as the "score".) I want to find out who has the highest or lowest score.
I have written a reduce function like so:
function(keys, values) {
var len = values.length;
return values[len - 1];
}
I know there's _stat and the like, but these are not possible in my application (this is a slimmed down, hypothetical example).
Usually when I run this reduce, i will get either 'sam' or 'jill' depending on whether descending is set. This is what I want. However, in large data-sets, sometimes I get someone from the middle of the list.
I suspect this is happening on rereduce. I had assumed that when rereduce has been run, the order of results is preserved. However, I can find no assurances that this is the case. I know that on rereduce, the key is null, so by the normal sorting rules they would not be sorted. Is this the case?
If so, any advice on how to get my highest scorer?
Yeah, I don't think sorting order is guaranteed, probably because it cannot be guaranteed in clustered environments. I suspect the way you're using map/reduce here is a little iffy, but you should post your view code if you really want a good answer here.

Does CouchDB's group=true prevent rereduce?

CouchDB's map functions emit key/value pairs:
function(doc) {
emit(doc.date, 1);
}
Potentially, there could be many key/value pairs with the same key. Setting group=true while querying a view groups key/value pairs with the same key into the same reduce:
function(keys, values, rereduce) {
return sum(values);
}
Does this mean that with group=true (or for any group_level > 0), there will be exactly one reduce per key?
Or does the grouping only guarantee that all reduces will have homogeneous keys, and that there could still be one or more rereduces?
I am working with a reduce function that is not commutative, but which will not have a large number of records per key. I was hoping that I would be able to set group=true and then control the order of operation within a single reduce. If there will be rereduces, then that plan does not make sense.
group=true roughly means "Hey, Couch! Group this map in the way there all keys will be distinct, but don't miss any case of them!" and actually equals to group_level=999 (see docs).
While you may not guess with proper group_level and strip some key items (if key is an array it makes sense), group takes care of this for you and rereduce wouldn't be applied.
Also, your reduce function could be replaced with the built-in _sum - it's implemented in Erlang and is much faster.

Need Explanation of couchdb reduce function

From http://wiki.apache.org/couchdb/Introduction_to_CouchDB_views
The couchdb reduce function is defined as
function (key, values, rereduce) {
return sum(values);
}
key will be an array whose elements
are arrays of the form [key,id]
values will be an array of the values
emitted for the respective elements
in keys
i.e. reduce([ [key1,id1], [key2,id2], [key3,id3] ], [value1,value2,value3], false)
I am having trouble understanding when/why the array of keys would contain different key values. If the array of keys does contain different key values, how would I deal with it?
As an example, assume that my database contains movements between accounts of the form.
{"amount":100, "CreditAccount":"account_number", "DebitAccount":"account_number"}
I want a view that gives the balance of an account.
My map function does:
emit( doc.CreditAccount, doc.amount )
emit( doc.DebitAccount, -doc.amount )
My reduce function does:
return sum(values);
I seem to get the expected results, however I can't reconcile this with the possibility that my reduce function gets different key values.
Is my reduce function supposed to group key values first? What kind of result would I return in that case?
By default, Futon "groups" your results, which means you get a fresh reduce per key—in your case, an account. The group feature is for exactly this situation.
Over the raw HTTP API, you will get one total reduce for all accounts which is probably not useful. So remember to use group=true in your own application to be sure you get summaries per account.

Resources