Steve Anderson
Steve Anderson

Reputation: 334

Return a document with the largest value

I've got a series of documents that have a version field.

{
 "_id": "xxx",
 "_rev": "6-4bdeb530234c454ae2f16d77ba577428",
 "name": "glossary",
 "locale": "en-us",
 "version": "186.0",
 "title": "Glossary",
 ...
}

I'd like to be able to return the document where name is glossary that has the largest version.

If I make the map function like this:

function(doc) {
  emit(doc.name, doc);
  }

and do a reduce on it, I can figure out which document has the latest version, but when I try to return it (return latest_doc), I get a reduce_overflow_error error.

It seems like I need to do this via a map function only, but I can't figure out how to return a single document with the highest value from the map.

I'm sure there's an easy way to do this, but I haven't been able to figure it out.

Can you help me get the latest version of my glossary document?

Upvotes: 0

Views: 158

Answers (1)

Akshat Jiwan Sharma
Akshat Jiwan Sharma

Reputation: 16000

reduce_overflow_error is couchdb's way of telling you that you are not using reduce in a way it is supposed to be used. From the wiki

Reduce is a powerful feature of CouchDB but is often misused which leads to performance problems. From 0.10 onwards, CouchDB uses a heuristic to detect reduce functions that won't scale to give the developer an early warning. A reduce function must reduce the input values to a smaller output value. If you are building a composite return structure in your reduce, or only transforming the values field, rather than summarizing it, you might be misusing this feature

Try this map function

function(doc) {
 emit([doc.name,doc.version], doc._id);

}

query it with

/view-name?include_docs=true&startkey=["glossary",{}]&endkey=["glossary"]&descending=true&limit=1

This will give you the the file with the highest version number. Remove the limit parameter if you want more files.

Upvotes: 2

Related Questions