Chapter 21. View Cookbook for SQL Jockeys
This is a collection of some common SQL queries and how to get the same result in CouchDB. The key to remember here is that CouchDB does not work like an SQL database at all and that best practices from the SQL world do not translate well or at all to CouchDB. This chapter’s “cookbook” assumes that you are familiar with the CouchDB basics such as creating and updating databases and documents.
Using Views
How you would do this in SQL:
CREATE TABLE
or:
ALTER TABLE
Using views is a two-step process. First you
define a view; then you query
it. This is analogous to defining a table structure (with indexes) using
CREATE TABLE or ALTER TABLE and
querying it using an SQL query.
Defining a View
Defining a view is done by creating a special document in a
CouchDB database. The only real specialness is the
_id of the document, which starts with
_design/—for example,
_design/application. Other than that, it is just a
regular CouchDB document. To make sure CouchDB understands that you are
defining a view, you need to prepare the contents of that design
document in a special format. Here is an example:
{"_id":"_design/application","_rev":"1-C1687D17","views":{"viewname":{"map":"function(doc) { ... }","reduce":"function(keys, values) { ... }"}}}
We are defining a view viewname. The definition
of the view consists of two functions: the map
function and the reduce function. Specifying a reduce function is optional. We’ll look at the nature of the functions ...