How to sum view values ​​in a date range using couchdb?

If I have a map function emitting a timestamp as a key ad, a number as a document, how do I get the sum of the values ​​that select a date range?

EDIT document example:

{
   "_id": "[2011, 6, 7, 10, 55]",
   "_rev": "1-f87d54608d36cd2e28add67e88e416a4",
   "volt": 107,
   "ampere": 23.5
}

view:

{
   "_id": "_design/power",
   "_rev": "1-7788287ab51c480c725498eba4f79ddb",
   "language": "javascript",
   "views": {
       "watt": {
           "map": "function(doc) {\n  emit(doc._id, doc.volt * doc.ampere);\n}"
       }
   }
}

I need to request, for example: hourly average in the month of March.

+5
source share
2 answers

I see a problem with your map function emitting your _id as a key when you want to make a range request for date information. You must save the date information in a separate field. _id must be a string, and you cannot correctly execute the startkey-endkey request.

Sort of:

{
   "_id": "997b9f758899f102ab58570686001bc2",
   "_rev": "1-f87d54608d36cd2e28add67e88e416a4",
   "date": [2011, 6, 7, 10, 55],
   "volt": 107,
   "ampere": 23.5
}

:

{
   "_id": "_design/power",
   "_rev": "1-7788287ab51c480c725498eba4f79ddb",
   "language": "javascript",
   "views": {
       "watt": {
           "map": "function(doc) {\n  emit(doc.date, doc.volt * doc.ampere);\n}",
           "reduce": "_sum"
       }
   }
}

, , [, , , , ]. 1 , 2 .. , .

GET db/_design/power/_view/watt?group_level=2

- :

{"rows":[
 {"key":[2011,4],"value":1988.5},
 {"key":[2011,5],"value":1988.5},
 {"key":[2011,6],"value":7778.0}
]}

, -.

GET db/_design/power/_view/watt?startkey=[2011,4]&endkey=[2011,6]

{"rows":[
{"key":null,"value":3977.0}
]}

, .

GET db/_design/power/_view/watt?startkey=[2011,4]&endkey=[2011,6]&group_level=2

{"rows":[
{"key":[2011,4],"value":1988.5},
{"key":[2011,5],"value":1988.5}
]}

, ... .

CouchDB HTTP View API -

EDIT:

, . .

GET db/_design/power/_view/watt?startkey=[2011,4]&endkey=[2011,6]&group_level=4

{"rows":[
{"key":[2011,4,9,11],"value":1988.5},
{"key":[2011,5,9,11],"value":1988.5}
]}

, , , , startkey/endkey group_level.

+6

_sum reduce:

"reduce":"_sum"

startkey endkey:

GET db/_design/power/_view/watt?group_level=2&startkey=[2011,3]&endky=[2011,4]&inclusive_end=false

.

0

All Articles