views:

257

answers:

2

What is the best way to store ordered documents in CouchDB?

Say I have 100 articles and I want to order them by just visibly placing them in an order I like, or I have 10,000 images and I want them to appear in a specific order other than by date/category/etc. Is this best stored at the parent ("page" or "album" level), or child (image/article) level?

Should it be more like this:


{
    _id: myPage;
    articles: [myArticle14, myArticle5, myArticle2, myArticle20...];
}
or this:

{
    _id: myArticle14;
    position: 1;
}

... where articles: [myArticle14, myArticle5, myArticle2, myArticle20...]; are the _id's of te actual Article documents.

What are the benefits/drawbacks of each, and which do you find is easier to use as the app grows?

+1  A: 

Use one document per article, assuming it contains non-trivial data. One big "container" document is not a good idea - you'd waste lots of revisions for each little update of any article data. It'd also make conflict resolution a hell.

I'm not exactly getting what do you mean by ordering issue. Choosing a base representation of your data, ie. packing it into documents is one thing. Consider one document as an atomic entity - you can store its new revision in a consistent way. Document defines the granularity of data which will be created, updated, replicated and possibly conflicted with revisions from other sources. But it has nothing to do with ordering, except for the fact that by choosing a particular form of document id you have one ordering for free. But you can ignore it as well and choose auto-generated ids meaningless in your problem domain. You will define orderings for different purposes as views, anyway. That's different story.

Wojciech Kaczmarek
+1  A: 

First solution.

Advantage: You can't have two articles on one position.

Disadvantage: To get articles in order, you need to get all the articles from DB and then filter only ones you need, or you need to call as many queries as articles you want to display on the page.

Second solution

Advantage: You can get all documents for one page in one query. Just create view where key is made of page and position and use startKey and endkey parameters to get only articles you need.

Disadvantage: It is possible to make a mistake and have more articles with the same position.

I would choose second solution.

amorfis
Your answer for the first solution is not exactly valid. We can have all articles in one document and still have the view which emits all articles with different keys. Nothing prevents us from doing many emits from one doc and it's a common technique. While I prefer second solution as well, it's good to remember that choosing doc representation is mostly about desired atomicity, and for quering one would end up with (lots of) views anyway.
Wojciech Kaczmarek