Filtering posts by timestamp and userId

I have the following object in Couchbase:

       "postReplyId": "Reply_9AE1F47E585522FD1D2EFFEA7671C0855BBFDA991698B23886E37D1C65DAC8AF_1375468399745",
       "userId": "User_9AE1F47E585522FD1D2EFFEA7671C0855BBFDA991698B23886E37D1C65DAC8AF",
       "postId": "Message_9AE1F47E585522FD1D2EFFEA7671C0855BBFDA991698B23886E37D1C65DAC8AF_1375457606125",
       "post_reply_message": "Testing",
       "attachments": {
       "images": [
       "audio": [
       "videos": [
       "upVoters": [
       "downVoters": [
       "upVotes": 0,
       "report": 0,
       "reporters": [
       "timestamp": 1375468399745,
       "mtype": "reply"

I would like to have a view and return all the posts created during the last `30 minutes` by the user `x`

I did:

    function (doc, meta) {
      if(doc.mtype == "reply") {
        var dt = new Date();
        if((dt.getTime() - doc.timestamp) < 1800000 )
  	    emit(doc.userId, doc);

and i pass the userIds as multiple keys in the URL, but I get old results

Can someone suggest a solution?

1 Answer

« Back to question.

var dt = new Date(); will represent not date now, but it will be the date when index process had happened. So it can be any time, but not that time, what you expect to see there.
1. Use date range requests and don't use "new Date()". Map function should contain something like emit([doc.userId, doc.timestamp], null);
2. Why are you using such long userIds? Using 32 digits guids is enough for generating unique ids.
3. Try to avoid emitting "doc" in map function like emit(doc.userId, doc)

Thanks for your answer but I have a quick question, how I will be able to check the timestamp difference?

I only need posts created during the last 30 minutes.

Can you provide us a small example after emitting two keys?

if((dt.getTime() - doc.timestamp) < 1800000 )

Here is your map function:

emit([doc.userId, doc.timestamp], null);

Then on app side before quering view get something like C#'s DateTime.Now. Let it be var now

So i.e. for user with id = 1 your query you will need:

startKey = [1, now.AddMinutes(-30)] //substract from now 30 minutes
endKey = [1, now]

And then query your view with that startKey and endKey.

See this for more examples