CouchDB 查询以获取具有 MAX 时间戳的文档

CouchDB query to get the doc with MAX timestamp

我的 CouchDB 文档格式如下,根据价格变化,可以有多个具有相同 product_id & store_id

的文档

{ "_id": "6b645d3b173b4776db38eb9fe6014a4c", "_rev": "1-86a1d9f0af09beaa38b6fbc3095f06a8", "product_id": "6b645d3b173b4776db38eb9fe60148ab", "store_id": "0364e82c13b66325ee86f99f53049d39", "price": "12000", "currency": "AUD_$", "time": 1579000390326 }

我需要得到 latest document(按 time - 时间戳)给定 product_id & store_id

为此,对于我当前的解决方案,我必须执行以下两个查询;

  1. 获取最新的时间戳。 returns 给定 product_id & store_id

    的最新时间戳

    "max_time_by_product_store_id": { "reduce": "function(keys, values) {var ids = [] values.forEach(function(time) { if (!isNaN(time)){ ids.push(time); } }); return Math.max.apply(Math, ids) }", "map": "function (doc) {emit([doc.store_id, doc.product_id], doc.time);}" }

  2. 基于最新的timestamp,我再次查询获取具有三个参数store_idproduct_idtime的文档作为下面,

    "store_product_time": { "map": "function (doc) { emit([doc.store_id, doc.product_id, doc.time]); }" }

这对我来说非常有效,但我的问题是我需要执行两个数据库查询来获取文档并寻找一种解决方案来在一个数据库查询中获取文档。

在 CouchDB 选择器中也无法通过 MAX 值获取文档。

使用 CouchDB 的 /db/_find,您可以将 sort 结果和 limit 结果降序到一个文档,如下所示:

{
   "selector": {
      "_id": {
         "$gt": null
      }
   },
   "sort": [
      {
         "time": "desc"
      }
   ],
   "limit": 1
}

CURL

curl -H 'Content-Type: application/json' -X POST http://localhost:5984/<db>/_find -d '{"selector":{"_id":{"$gt":null}},"sort":[{"time": "desc"}],"limit": 1}'

Please note that an index must previously be created for the sort field time (see /db/_index).