CouchDB: Return Newest Documents of Type Based on Timestamp

前端 未结 3 477
清酒与你
清酒与你 2021-01-15 14:33

I have a system that accepts status updates from a variety of unique sources, and each status update creates a new document in the following structure:

{
 \"         


        
3条回答
  •  半阙折子戏
    2021-01-15 15:07

    You can get the latest timestamp for every source using the _stats built-in reduce function, then do another query to get the documents. Here's the views:

    "views": {
      "latest_update": {
        "map": "function(doc) { if (doc.type == 'status_update') emit(doc.source_id, doc.timestamp); }",
        "reduce": "_stats"
      },
      "status_update": {
        "map": "function(doc) { if (doc.type == 'status_update') emit([doc.source_id, doc.timestamp], 1); }"
      }
    }
    

    First query latest_update with group=true, then status_update with something like (properly url-encoded):

    keys=[["truck123",TS123],["truck234",TS234],...]&include_docs=true
    

    where TS123, and TS234 are the values of max returned by latest_update.

提交回复
热议问题