I am still learning cloudant and need a little help to figure out what will be the right tool to use to get the latest document (based on timestamp in the document) with a specific field value.
I have read through the views documentation and understand I can create a view whose key is an array with data ["field-value","timestamp"]? And then at query time, query by the key with descending order and limit the docs to 1? or is there a better way to do it? I will be using partitioned db.
Sample data when queried for documents with key:"k1":
{
"id": "55e9fd410b0df870409e0d92bf6a8318",
"key": "k1",
"time": "2019-08-06T19:11:16.556Z"
},
{
"id": "77a3ba0b77f1c740f68bac46a2a307ee",
"key": "k1",
"time": "2019-08-06T19:11:16.539Z"
}
Desired output:
{
"id": "55e9fd410b0df870409e0d92bf6a8318",
"key": "k1",
"time": "2019-08-06T19:11:16.556Z"
}
You can achieve that in several ways. The most flexible one is to create a view that emits a vector-valued key containing the key and yyyy, mm, dd or whichever bits you care about from the time stamp:
function (doc) {
var d = new Date(doc.timestamp);
emit([
doc.product_id,
d.getFullYear(),
d.getMonth()+1,
d.getDate()], null);
}
}
With a reduce of say _count
you can then also aggregate over time. This approach is described well in an old blog post from Mike Miller.
If you don't care about aggregation you can either just emit an epoch second as the key, or construct time-sortable ids, as suggested by Glynn Bird in another Cloudant blog post.