按值对CouchDB结果进行排序 [英] Sorting CouchDB result by value

查看:436
本文介绍了按值对CouchDB结果进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是CouchDB(通常是NoSQL)的新手,并且正在创建一个简单的Node.js + express + nano应用程序,以了解它。这是一个简单的书籍集合,其中包含标题和作者两个字段。

I'm brand new to CouchDB (and NoSQL in general), and am creating a simple Node.js + express + nano app to get a feel for it. It's a simple collection of books with two fields, 'title' and 'author'.

示例文档:

{
   "_id": "1223e03eade70ae11c9a3a20790001a9",
   "_rev": "2-2e54b7aa874059a9180ac357c2c78e99",
   "title": "The Art of War",
   "author": "Sun Tzu"
}

缩小函数:

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

由于CouchDB按键排序并支持'descending = true查询参数,很容易在UI中实现过滤器以切换标题的排序顺序,这是我的结果集中的关键。用户界面如下:

Since CouchDB sorts by key and supports a 'descending=true' query param, it was easy to implement a filter in the UI to toggle sort order on the title, which is the key in my results set. Here's the UI:

书籍列表带有按升序或降序对标题进行排序的链接

但是我完全不知道如何为作者字段执行此操作。

But I'm at a complete loss on how to do this for the author field.

我见过这个问题,可以帮助海报按数字减少值进行排序,并且我阅读了一篇博文,该博文使用列表还按化简值进行排序,但是我没有看到任何对不化简的字符串值进行排序的方法。

I've seen this question, which helped a poster sort by a numeric reduce value, and I've read a blog post that uses a list to also sort by a reduce value, but I've not seen any way to do this on a string value without a reduce.

推荐答案

如果要按特定属性排序,则需要确保该属性是键(或者,对于数组键,

If you want to sort by a particular property, you need to ensure that that property is the key (or, in the case of an array key, the first element in the array).

我建议使用sort键作为键,并发出nul l值,并使用 include_docs 来获取完整文档,以允许您在UI中显示多个属性(这也使反序列化的值保持一致,因此您无需更改方式您可以根据排序顺序来处理返回值。)

I would recommend using the sort key as the key, emitting a null value and using include_docs to fetch the full document to allow you to display multiple properties in the UI (this also keeps the deserialized value consistent so you don't need to change how you handle the return value based on sort order).

您的地图函数如下所示。

Your map functions would be as simple as the following.

按作者排序:

function(doc) {
  if (doc.title && doc.author) {
    emit(doc.author, null);
  }
}

按标题排序:

function(doc) {
  if (doc.title && doc.author) {
    emit(doc.title, null);
  }
}

现在,您只需要更改要调用的视图并确保在查询中使用 include_docs = true 参数。

Now you just need to change which view you call based on the selected sort order and ensure you use the include_docs=true parameter on your query.

您还可以使用通过一次同时发射它们来实现此目的的单个视图...

You could also use a single view for this by emitting both at once...

emit(["by_author", doc.author], null);
emit(["by_title", doc.title], null);

...,然后使用复合键进行查询。

... and then using the composite key for your query.

这篇关于按值对CouchDB结果进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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