CouchDB“加入"两份文件 [英] CouchDB "Join" two documents

查看:27
本文介绍了CouchDB“加入"两份文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件看起来有点像:

I have two documents that looks a bit like so:

Doc
{
  _id: AAA,
  creator_id: ...,
  data: ...
}

DataKey
{
  _id: ...,
  credits_left: 500,
  times_used: 0,
  data_id: AAA
}

我要做的是创建一个视图,它允许我传递 DataKey id (key=DataKey _id) 并获取 DataKey 和 Doc 的信息.

What I want to do is create a view which would allow me to pass the DataKey id (key=DataKey _id) and get both the information of the DataKey and the Doc.

我的尝试:

我首先尝试将 DataKey 嵌入到 Doc 中,并使用如下映射函数:

I first tried embedding the DataKey inside the Doc and used a map function like so:

function (doc)
{
  if (doc.type == "Doc")
  {
    var ids = [];
    for (var i in doc.keys)
      ids.push(doc.keys[i]._id);

    emit(ids, doc);
  }
}

但是我遇到了两个问题:

But i ran into two problems:

  1. 每个 DataKey 可以有多个使用 startkey=[idhere...]而 endkey=[idhere..., {}] 没有工作(仅当密钥发生时才有效成为数组中的第一个).
  2. 所有数据键都必须是唯一的,我不希望像 {_id = datakey} 那样制作单独的文档来保留键.

有没有人知道我可以如何做到这一点?如果有任何不清楚的地方,请告诉我.

Does anyone have ideas how I can accomplish this? Let me know if anything is unclear.

-----编辑-----

我忘了提到在我的应用程序中我不知道 Doc ID 是什么,所以我需要能够搜索 DataKey 的 ID.

I forgot to mention that in my application I do not know what the Doc ID is, so I need to be able to search on the DataKey's ID.

推荐答案

我觉得你想要的是

function (doc)
{
  if (doc.type == "Doc")
  {
    emit([doc._id, 0], doc);
  }

  if(doc.type == "DataKey")
  {
    emit([doc.data_id, 1], doc);
  }
}

现在,使用 key=["AAA"] 查询视图,您将看到所有文档的列表.第一个将是真正的Doc"文档.其余的都是引用第一个文档的DataKey"文档.

Now, query the view with key=["AAA"] and you will see a list of all docs. The first one will be the real "Doc" document. All the rest will be "DataKey" documents which reference the first doc.

这是一种常见的技术,称为 CouchDB 视图排序规则.

This is a common technique, called CouchDB view collation.

这篇关于CouchDB“加入"两份文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆