如何在CouchDB中实现文档关联查询并统计同一组织者的活动数量
解决方案
CouchDB可通过MapReduce视图实现该统计需求,具体操作如下:
基础方案(无需校验组织者存在,性能最优)
如果你已经确认用于统计的邮箱对应有效组织者,直接用该方案即可:
步骤1:创建统计视图
在对应数据库中新建设计文档,例如路径为_design/eventStats,添加视图:
- 视图ID:
countByOrganizer - map函数:
function(doc) { // 筛选活动文档,以邮箱为键输出计数 if (doc.doc_type === 'Event' && doc.email) { emit(doc.email, 1); } }
- reduce函数:直接填写内置函数
_sum
步骤2:查询单组织者活动数
调用视图时传入以下参数即可获取指定邮箱的活动总数:
key="目标邮箱地址"比如key="xxx@gmail.com"reduce=true
如果需要批量获取所有组织者的活动统计,添加group=true参数即可返回所有邮箱对应的活动数量列表。
进阶方案(仅统计有对应组织者的活动)
如果需要确保统计的活动对应的邮箱确实在User文档中存在,修改视图函数即可:
map函数:
function(doc) { if ((doc.doc_type === 'Event' || doc.doc_type === 'User') && doc.email) { emit(doc.email, { type: doc.doc_type, eventCount: doc.doc_type === 'Event' ? 1 : 0 }); } }
自定义reduce函数:
function(keys, values, rereduce) { let hasValidUser = false; let totalEvents = 0; for (const item of values) { if (rereduce) { hasValidUser = hasValidUser || item.hasValidUser; totalEvents += item.totalEvents; } else { if (item.type === 'User') hasValidUser = true; totalEvents += item.eventCount; } } return rereduce ? {hasValidUser, totalEvents} : (hasValidUser ? totalEvents : 0); }
查询方式和基础方案一致,返回结果即为对应有效组织者的活动总数。
内容的提问来源于stack exchange,提问作者LeNicow
相关产品推荐
相关产品推荐

