从CouchDB视图获取具有最大字段值的文档列表 [英] Getting a list of documents with a maximum field value from CouchDB view

查看:85
本文介绍了从CouchDB视图获取具有最大字段值的文档列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在CouchDB数据库中有这样的博客条目:

Let's say I have blog entries like these in my CouchDB database:


{"name":"Mary", "postdate":"20110412", "subject":"this", "message":"blah"}
{"name":"Joe", "postdate":"20110411", "subject":"that", "message":"yadda"}
{"name":"Mary", "postdate":"20110411", "subject":"and this", "message":"blah-blah"}
{"name":"Joe", "postdate":"20110410", "subject":"And other thing", "message":"yada-yada"}
{"name":"Jane", "postdate":"20110409", "subject":"Serious stuff", "message":"Not really"}

获取所有帖子列表非常容易.但是,如何获得所有用户的最新帖子列表?

It's pretty easy to get a list of all posts. But how do I get a list of latest posts from all the users?

喜欢:


{"name":"Mary", "postdate":"20110412", "subject":"this", "message":"blah"}
{"name":"Joe", "postdate":"20110411", "subject":"that", "message":"yadda"}
{"name":"Jane", "postdate":"20110409", "subject":"Serious stuff", "message":"Not really"}

推荐答案

尝试使用此地图功能:

function(doc) {
  if (doc.postdate && doc.name) {
    emit([doc.name, doc.postdate], 1);
  }
}

和以下reduce函数:

and the following reduce function:

function(keys, values, rereduce) {
  var max = 0,
      ks = rereduce ? values : keys;

  for (var i = 1, l = ks.length; i < l; ++i) {
    if (ks[max][0][1] < ks[i][0][1]) max = i;
  }
  return ks[max];
}

并用group_level=1进行查询.它为您提供了帖子的_id,然后您可以通过 keys参数或使用POST .

and query it with group_level=1. It gives you the _id of the posts, then you can retrieve them all with a single query with the keys parameter or using a POST.

我不确定这是否是最好的方法,但似乎可行.

I am not sure if this is the best approach, but it seems to work.

更新:修复了映射以正确处理缩小的问题.

UPDATE: fixed map to handle rereduce correctly.

这篇关于从CouchDB视图获取具有最大字段值的文档列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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