You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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

简化替代方案:客户端处理关联

如果不想编写列表函数,也可以直接查询视图并在客户端处理:

  1. 调用视图并携带include_docs=true参数:
http://localhost:5984/你的数据库名/_design/joins/_view/person_with_dept?include_docs=true
  1. 在客户端代码中,先收集所有部门文档到映射表,再遍历人员文档,将对应部门信息嵌入,最终生成目标结构。

内容的提问来源于stack exchange,提问作者PS24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 13:06:17