我有一个cloudant DB,每个文档看起来像:
{
"_id": "2015-11-20_attr_00",
"key": "attr",
"value": "00",
"employeeCount": 12,
"timestamp": "2015-11-20T18:16:05.366Z",
"epocTimestampMillis": 1448043365366,
"docType": "attrCounts"
}
Run Code Online (Sandbox Code Playgroud)
对于给定的属性,有一个员工计数.正如您所看到的,我每天都有相同属性的记录.我正在尝试创建一个视图或索引,它将为我提供此属性的最新记录.这意味着如果我在2015-10-30和2015-11-10中插入了一条记录,那么返回给我的记录只是2015-11-10时间戳记录的员工数量.
我试过了视图,但我得到的每个属性的所有条目不仅仅是最新的.我没有看索引,因为我认为它们没有预先计算.我将从客户端查询此信息,因此预先计算(如视图)非常重要.
任何指导都将非常感激.谢谢
小智 8
我在这里创建了一个测试数据库.只需确保在将JSON文档插入Cloudant(或CouchDB)时,您的时间戳不是字符串,而是JavaScript数据对象:
https://examples.cloudant.com/latestdocs/_all_docs?include_docs=true
我建立了这样的搜索索引(将设计文档命名为"summary",将搜索索引命名为"latest"):
function (doc) {
if ( doc.docType == "totalEmployeeCounts" && doc.key == "div") {
index("division", doc.value, {"store": true});
index("timestamp", doc.timestamp, {"store": true});
}
}
然后这是一个只返回每个部门的最新记录的查询.请注意,限制值将适用于每个组,因此如果有limit = 1,如果有4个组,您将获得4个文档而不是1个.
https://examples.cloudant.com/latestdocs/_design/summary/_search/latest?q=*:*&limit=1&group_field=division&include_docs=true&sort_field=-timestamp