CouchDB Group Level and Key Range

2020-07-10 06:12发布

问题:

Can anyone explain to me why the following doesn't work:

Assuming the following document structure:

{
   "_id": "520fb089a6cb538b1843cdf3cca39a15",
   "_rev": "2-f96c27d19bf6cb10268d6d1c34799931",
   "type": "nosql",
   "location": "AZ",
   "date": "2012/03/01 00:00:00",
   "amount": 1500
}

And a Map function defined like so:

function(doc) {
  var saleDate = new Date(doc.date);
  emit([doc.location,saleDate.getFullYear(),saleDate.getMonth()+1],doc.amount);
}

And using the built in _sum function for the reducer.

When you execute this (with group=true) you get results like this:

{"rows":[
{"key":["AZ",2012,2],"value":224},
{"key":["AZ",2012,3],"value":1500},
{"key":["WA",2011,12],"value":1965},
{"key":["WA",2012,1],"value":358}
]}

Now if you change the query to something like this:

http://127.0.0.1:5984/default/_design/nosql/_view/nosql_test?group_level=2

You get results like this:

{"rows":[
{"key":["AZ",2012],"value":1724},
{"key":["WA",2011],"value":1965},
{"key":["WA",2012],"value":358}
]}

So with that in mind if I wanted to find out all sales in 2011 for "WA" could I not execute something like this:

http://127.0.0.1:5984/default/_design/nosql/_view/nosql_test?group_level=2&key=["WA",2011]

This example has been taken from the useful videos over at NoSQL tapes.

http://nosqltapes.com/video/understanding-mapreduce-with-mike-miller

回答1:

You always need to give a range of keys, because filtering is done on map's results, not on reduce.

For example, the following parameters should work (if properly url-encoded):

?group_level=2&startkey=["WA",2011]&endkey=["WA",2011,{}]

You can read about view collation to understand how it works.