Document-Oriented Persistence with CouchDB

… a scalable, NoSql database


leave a comment »

A database in CouchDB is simply a collection of documents. election-2005 is a database containing results from all UK constituencies for the 2005 election, taken from

Futon Overview


Each document has a unique ID (in this case I’m using the constituency name), and a revision number (shown in green) which is used to provide concurrency control.


A constituency record, showing total electorate plus votes for con, lab, lib, Plaid Cymru (pc), and others.


The same record in its native JSON format.


Here’s how to query the collection: in this case to get all constituencies, ordered by number of Conservative votes. CouchDB requires us to supply a Map function, which ranges of the document collection, and emits a set of key-value pairs. This creates an index on this value in the B+ tree.


Just in case you’re interested, the constituency with the highest number of Conservative votes is the Isle of Wight.


Now, let’s look at a where clause. Let’s say you want to get all constituencies where number of Conservative votes is between 1000 and 2000. What we want is to retrieve a sub-set from the index we created a minute ago. To do this, we append a query string on the end of the url: startkey=1000&endkey=2000.


Finally, here is an aggregate of all Conservative votes (8,782,198). To do this, we use a Reduce function, which sums the values produced by the Map function.



Written by klena02

February 1, 2010 at 9:59 am

Posted in CouchDB

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: