Posts Tagged ‘Javascript’

The thrill of a new technology: CouchDB

It has been a long time since I fell in love with a new technology (maybe Ruby on Rails when it first came out?), and the time I am spending with CouchDB lately has been a nice return to the pleasure of programming.

I’ll probably write some in-depth articles on Document based DBs later, but let me show you how complex operations on relational DBs can become really simple with a document based approach.

Let’s say you have a db of tagged objects, and you want to get a report with a “per tag” distribution of your objects. In a relational environment you would need at least three tables, objects, tags and a join table and a select operation involving two joins to get the results you needed:

SELECT tags.name, group_concat(people.name) 
FROM tags 
INNER JOIN tags_people ON tags.id = tags_people.tag_id
INNER JOIN people ON people.id = tags_person.id 
GROUP BY tags.name

This isn’t rocket science but I guess not everyone knows about group_concat :)

In a document based environment I would just have a document for each person, with a tags property that holds an array of tags. The map and reduce functions would look like this:

// map
function(doc) {
  if (doc['couchrest-type'] == 'Person' && doc.tags) {
    doc.tags.forEach(function(tag) {
      emit(tag, doc.name);
    }
  }
}
 
// reduce
function(keys, values, rereduce) {
  return values;
}

Using Javascript to manipulate data may seem counter intuitive, but as you can see we have a much simpler datastore (just people documents thrown in the db) and an easy way of manipulating them to extract the info we need.

I love CouchDB.