In the last few years there has been a proliferation of noSQL databases. Searching on Google for site:news.ycombinator.com nosql
yields over 2,500 hits, many of which include include posts asking when you’d want to use a noSQL database. If you’re used to a relational database it might seem like an unnecessary burden to learn another database paradigm, but there’s one open source noSQL database that I think is not only worth the burden, but is a perfect fit for Node.js development: Riak (pronounced “REE-ack”).
Why is Riak a Good Fit with JavaScript and Node.js?
Riak-js makes storing JavaScript objects easy. There is no need to JSON.stringify()
a JavaScript object when saving it, or applying JSON.parse()
when retrieving.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
In the above example, a riak-js client is created and a post object is created. The post object is saved into the ‘posts’ bucket, with its id as its key. To retrieve the post, the bucket and key are referenced.
Using JavaScript in the client, and the server are nice, and being able to easily save JavaScript objects is even better. Not having to switch between languages would certainly reduce annoying syntactic problems. This would also allow you to write the entire stack in JavaScript, CoffeeScript or ClojureScript, giving you several programming paradigms to choose from.
If you decided to use Backbone.js on the server, calling toJSON()
on a Backbone model would allow you to easily store the model in the Riak.
Why Riak?
At this point you might be wondering why you’d want to use Riak when CouchDB also has a JavaScript interface and can do some of the above. As Damien Katz, the creator of CouchDB has pointed out, CouchDB is slow and can’t “scale-out on it’s own”. In contrast, Riak was built for replication and scaling out. In fact, people at Basho, the company behind Riak, indicate that adding new nodes actually increases throughput.
Additional Features of Riak
Saving JavaScript objects and easy scaling are both good fits with node.js but Riak has some additional features, such as buckets and links, that make retrieval convenient. With buckets the following functions become possible:
1 2 3 4 5 6 7 8 |
|
Another interesting property of Riak, is it’s concepts of links. A link establishes a “one-way relationships between objects in Riak”. For instance, say we wanted to link similar posts the following would do:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Conclusions
While the above assessment is pretty rosey, Riak shouldn’t be the only database in your toolbox. Redis’ pub/sub and sorted sets are unmatched in Riak. If you’re running map/reduce over large datasets, you’re likely better off using Hadoop. Conversely if your already well-versed in SQL, and your data is relational, using Postgresql is probably a better fit. Despite those caveats being able to easily scale your database, and save JavaScript objects, is a pretty compelling reason to use Riak with Node.js