Couch DB Join operations like RDBMS

别等时光非礼了梦想. 提交于 2020-01-05 08:48:13

问题


I am using one DB for storing plain documents and another DB for storing only attachments. But i am storing attachment id in plain documents DB. Is there any way how to perform join operations two databases like RDBMS.

Thanks in Advance


回答1:


I know that it's possible to do joins within a database:

Here's a great post on that: http://www.cmlenz.net/archives/2007/10/couchdb-joins

The crux of it is that couchdb can order json values, including lists.

So let's take it from the top...CouchDB, as you know, stores JSON documents. It uses map functions to 'emit' ordered key value pairs (here is the page from the couchdb definitive guide: http://guide.couchdb.org/draft/views.html ) So let's take a super simple example, then the complex one we need for 'joins.'

This is a map function that goes through each doc in the db, checks if the doc has an author, and if it does, displays it's author and it's post. The result would be a list of 'key value pairs' ordered by keys, in this case authors (and it does so alphabetically).

function (doc) {
  if (doc.author) {
    emit(doc.author, doc.post);
  }
}

Now our complex example. This example assumes that the db has blog posts as json docs, and comments as separate json docs. The comments have a key called 'post' with the id of the blog post they belong to, much like foreign ids in mySQL.

function(doc) {
  if (doc.type == "post") {
    emit([doc._id, 0], doc);
  } else if (doc.type == "comment") {
    emit([doc.post, 1], doc);
  }
}

So what the heck is going on? So, first thing to notice is the 'else' part. This function actually maps blog posts and comments to the same view (ordered list of key value pairs).

'doc._id' is the id of a particular post, and 'doc.post' is the id of the post a comment belongs two. So the whole list is being ordered by the blog post's id.

If the doc.type is a 'blog post' it attaches a '0' in the array to denote so, and a '1' for docs that are 'comments.' Now here's the magic. The docs (posts, and comments) are ordered in one list of key value pairs, but because CouchDB can order arrays, it will slide those with a '1' (comments) in between one blog post and the next. Make sense?

Haha, so different from what we're used to, and this is just one creative solution. There are many other ways to create the result you might need. Hope this is helpful!




回答2:


There is no way to join, however you can consider storing attachments in the same database, or in the same documents which reference them.



来源:https://stackoverflow.com/questions/9428150/couch-db-join-operations-like-rdbms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!