【问题标题】:CouchDB query to get the doc with MAX timestampCouchDB 查询以获取具有 MAX 时间戳的文档
【发布时间】:2020-01-16 06:50:56
【问题描述】:

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

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

对于给定的product_idstore_id,我需要获得最新的 documenttime - 时间戳)

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

  1. 获取最新的时间戳。这将返回给定 product_idstore_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 值获取文档。

【问题讨论】:

    标签: mapreduce max couchdb couchapp


    【解决方案1】:

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

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

    卷曲

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

    请注意,必须事先为排序字段time 创建索引(请参阅/db/_index)。

    【讨论】:

    • 还有一件事是需要为time 创建一个索引,因为我们按time 键排序
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 2014-03-08
    相关资源
    最近更新 更多