我正试图在couchDB中获取一些统计信息。文件结构是
[{
_id: "1",
name: "Hotel A",
type: "hotel",
stars: 3,
flags: ["family-friendly","pet-friendly","green-hotel","sport"],
hotelType: "premium",
food: ["breakfast","lunch"]
}, {
_id: "2",
name: "Hotel B",
type: "hotel",
stars: 4,
flags: ["family-friendly","pet-friendly"],
hotelType: "budget",
food: ["breakfast"]
}, {
_id: "3",
name: "Hotel C",
type: "hotel",
stars: 5,
flags: ["family-friendly","pet-friendly"],
hotelType: "budget",
food: ["breakfast","lunch","dinner"]
}]
我如何获得酒店有多少“早餐”,“午餐”,“晚餐”并分类?我想得到这样的答案
{{breakfast:3},{lunch:2},{dinner:1}
}
或类似的东西。
答案 0 :(得分:2)
最简单的方法是使用map函数,为每个文档发出该文档中food
项的集合:
function (doc) {
doc.food.forEach(function (item) {
emit(iten, null)});
}
索引中的每个键现在只是一个食物项目。每个酒店和食品都有一把钥匙。到目前为止它看起来有点健谈:
$ curl -s 'http://localhost:5984/hotels/_design/so/_view/foods?reduce=false'
{"total_rows":6,"offset":0,"rows":[
{"id":"1","key":"breakfast","value":null},
{"id":"2","key":"breakfast","value":null},
{"id":"3","key":"breakfast","value":null},
{"id":"3","key":"dinner","value":null},
{"id":"1","key":"lunch","value":null},
{"id":"3","key":"lunch","value":null}
]}
但我们可以通过使用reduce步骤让couchdb为我们添加所有键。计算每个项目是一项常见的任务,它有一个特殊的erlang实现,只需使用“_count
”作为reduce函数,然后,在使用视图时,使用group=true
告诉它执行每个不同的密钥单独减少步骤。
$ curl -s 'http://localhost:5984/hotels/_design/so/_view/foods?group=true'
{"rows":[
{"key":"breakfast","value":3},
{"key":"dinner","value":1},
{"key":"lunch","value":2}
]}