Using an ISO Formated Date as a Doc _id

The ISO 8601 standard describes a useful scheme for representing a date string in a Year-Month-DayTHour:Minute:Second.microsecond format. For time-bound documents in a CouchDB database this can be a very handy way to create a unique identifier, since javascript can directly use it to create a Date object:

   "sum_by_day": {
       "map": "function(doc) {\n  var dt = new Date(doc._id);\n  emit([dt.getDate() doc.widget], 1);\n}",
       "reduce": "function(keys, values, rereduce) {\n   return sum(values)\n}"

. . . then simply use group_level to zoom in on whatever time you wish to use.

curl -X GET "http://localhost:5984/transactions/_design/widget_count/_view/toss?group_level=1"


curl -X GET "http://localhost:5984/transactions/_design/widget_count/_view/toss?group_level=2"


Another method is using parseint() and datetime.substr() to cut out useful values for a return key:

function (doc) {
    var datetime = doc._id;
    var year = parseInt(datetime.substr(0, 4));
    var month = parseInt(datetime.substr(5, 2), 10);
    var day = parseInt(datetime.substr(8, 2), 10);
    var hour = parseInt(datetime.substr(11, 2), 10);
    var minute = parseInt(datetime.substr(14, 2), 10);
    emit([doc.widget, year, month, day, hour, minute], 1);

If you have python views enabled, you can use the datetime module in the same way:

   1 def fun(doc):
   2     from datetime import datetime
   3     dt = datetime.strptime(doc._id, "%Y-%m-%dT%H:%M:%S.%f")
   4     yield [, dt.year, dt.month,, dt.hour, dt.minute], 1

. . .example with reduce function as it appears in the design doc:

    "doo_dad_finder": {
       "map": "def fun(doc):\n    from datetime import datetime\n    if doc['errors']:\n        dt = datetime.strptime(doc._id, '%Y-%m-%dT%H:%M:%S.%f')\n        for doo_dad in doc['doo_dads']:\n            yield [doo_dad, dt.year, dt.month, dt.hour], 1",
       "reduce": "def fun(keys, values, rereduce):\n    return sum(values)"

A nice example using a date within a document is found here: [dead link] copy

IsoFormattedDateAsDocId (last edited 2013-04-21 00:25:51 by 75-136-110-193)