如何通过CouchDB Views与Joins关联Person和Department并生成指定结果?
实现CouchDB中Person与Department文档的关联
1. 标准化文档结构
先给两类文档添加type字段用于区分,方便后续视图筛选:
- Person文档:
{ "_id": "person_1", "type": "person", "name": "Parnika", "city": "Delhi", "dept": "DevOps" }
- Department文档:
{ "_id": "dept_devops", "type": "department", "name": "DevOps", "city": "Delhi" }
2. 创建关联视图
在CouchDB中新建设计文档(例如_design/joins),在其中定义视图person_with_dept:
Map函数
该函数以部门名称作为关联键,输出文档类型和内容:
function(doc) { if (doc.type === "person") { emit(doc.dept, { type: "person", doc: doc }); } else if (doc.type === "department") { emit(doc.name, { type: "department", doc: doc }); } }
Reduce设置
将Reduce设为none即可,后续用列表函数处理结果。
3. 用列表函数格式化结果
在同一个设计文档_design/joins中添加列表函数format_person_dept,用于将关联后的文档整合成目标结构:
function(head, req) { var row; var result = {}; var deptMap = {}; // 先遍历所有部门文档,存入临时映射表 while (row = getRow()) { if (row.value.type === "department") { deptMap[row.key] = row.value.doc; } } // 重置游标,遍历人员文档并关联部门 start({ headers: { "Content-Type": "application/json" } }); reset(); while (row = getRow()) { if (row.value.type === "person") { var person = row.value.doc; result.Person = { name: person.name, city: person.city, Department: deptMap[person.dept] }; } } send(JSON.stringify(result)); }
4. 获取最终结果
通过以下URL访问列表函数,即可得到目标结构的结果:
http://localhost:5984/你的数据库名/_design/joins/_list/format_person_dept/person_with_dept
简化替代方案:客户端处理关联
如果不想编写列表函数,也可以直接查询视图并在客户端处理:
- 调用视图并携带
include_docs=true参数:
http://localhost:5984/你的数据库名/_design/joins/_view/person_with_dept?include_docs=true
- 在客户端代码中,先收集所有部门文档到映射表,再遍历人员文档,将对应部门信息嵌入,最终生成目标结构。
内容的提问来源于stack exchange,提问作者PS24
相关产品推荐
相关产品推荐

