I've got a background dealing with relational databases but lately began to dabble in CouchDB and was surprised at how some non-relational procedures, which may the simple in SQL, weren't first-class functions in CouchDB.

I'd appreciate you going for a moment to map each SQL statement below to the MapReduce equivalent.

SELECT COUNT(*) FROM products WHERE price < 20.00;
SELECT category, SUM(price) FROM products GROUP BY category;
UPDATE products SET price = 19.99 WHERE price = 20.00;
DELETE FROM products WHERE expires_at <= NOW();

The SELECT instructions are pretty easy. Bulk creates are a little more difficult. Generally, you will employ some view to retrieve the documents that should be transformed, then you will make use of the [cde] API to transmit all the new changes at the same time.

Also, consult the documentation regarding views for particulars based on how to problem queries. Including ordering, grouping, etc.


_bulk_docs

Map

SELECT COUNT(*) FROM products WHERE price < 20.00;

Reduce

function (doc) {
  if (doc.price < 20) {
    emit(doc.price);
  }
}

If you want this to utilize a random amount, not only 20, then you will want to emit the cost in most cases, and employ _count and startkey to limit your resultset.


endkey

Map

SELECT category, SUM(price) FROM products GROUP BY category;

Reduce

function (doc) {
  emit(doc.category, doc.price);
}

This map function basically uses the course because the key, using the cost because the value inside your key/value pair. The reduce function will prove to add in the prices for every different key.


_sum

Map

UPDATE products SET price = 19.99 WHERE price = 20.00;

When your application pulls lower the items in this view, you'll perform all of the manipulations inside your application code, then send back the outcomes in to the database through the function (doc) { if (doc.price == 20) { emit(doc.price); } } API.


_bulk_docs

Map

DELETE FROM products WHERE expires_at <= NOW();

For the way your store your date-time values, you may want to adjust the map function along with your query towards the view. Utilizing a timestamp (JS uses milliseconds rather than seconds) is most likely the quickest way to do this. Once you have setup your query, you'll give a new area to all these documents. function (doc) { emit(doc.expires_at); } . When you send this list into the database (again with _deleted: true) all of the specified documents is going to be erased.