【问题标题】:Filtering posts by timestamp and userId按时间戳和 userId 过滤帖子
【发布时间】:2013-08-06 10:18:43
【问题描述】:

我在 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"
}

我想查看并返回用户x在最后30 minutes期间创建的所有帖子

我做到了:

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

我将 userIds 作为 URL 中的多个键传递,但我得到了旧结果

有人可以提出解决方案吗?

【问题讨论】:

    标签: api indexing couchbase


    【解决方案1】:

    视图在文档被添加/修改时运行,并且仅在请求或自动更新时运行。它不会不断地重新运行,更重要的是,它不会为已添加的文档重新运行。因此,正如所写,您的视图将只包含旧结果。

    您需要发出所有文档并将时间戳作为发出的一部分包含在内,以便您可以将其用作对视图(时间范围)的查询的一部分。

    因此,在您的发出函数中,您可能会改为(未经测试的代码):

    function (doc, meta) {
      if (doc.mtype === "reply") {
        // dt will be when the document is processed by the view, which may
        // not when the document was added.
        var dt = new Date();  
        var year = dt.getFullYear();
        var month = dt.getMonth() + 1; // make month 1-12
        var day = dt.getDate();
        var hours = dt.getHours();
        var minutes = dt.getMinutes();
        var seconds = dt.getSeconds();
    
        // emit the full key, including the user id and the date of the document.
        emit([doc.userId, year, month, day, hours, minutes, seconds], doc._id);
      }
    }
    

    那么您的查询可能是这样的范围(为了便于阅读,分成几行):

    /salamis_db/_design/docs/_view/by_user_date?
         startkey=["the-userId", 2013, 8, 7, 10, 30, 0]
         &endkey=["the-userId", 2013, 8, 7, 11, 00, 00]
    

    虽然endkey 不是绝对必要的,但为了清楚起见,我将其保留。

    由于 Couchbase 视图的工作方式,视图可能并不总是包含所有数据(来自 here):

    不管 stale 参数,文档只能被索引 一旦文档被持久化到磁盘上,系统就会执行此操作。如果 文档还没有被持久化到磁盘,陈旧的文件不会被使用 强制这个过程。您可以使用观察操作来监控何时 文档被持久化到磁盘和/或在索引中更新。

    另外,请注意默认情况下不会立即将文档添加到视图中。阅读this了解更多信息。

    【讨论】:

    • 感谢您的全面回复。我想问一下我是否可以将多个用户 ID 用作startkeyendkey。在我使用 keys=["userId1", "userId2"] 之前
    • 很遗憾,您不能同时拥有用户列表和日期范围的过滤器。这些类型的查询最好留给关系数据库。
    • 很好的答案,请注意,当您有一个日期时,您还可以使用 javascript 函数 dateToArray(yourdate) ,记录在这里 couchbase.com/docs/couchbase-manual-2.1.0/…
    猜你喜欢
    • 1970-01-01
    • 2021-01-17
    • 2021-07-09
    • 1970-01-01
    • 2022-11-24
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    相关资源
    最近更新 更多