ruby - 使用redis存储结构化事件日志

标签 ruby data-structures redis

我对 Redis 有点陌生,如果这是基础知识,请原谅。

我正在开发一款应用程序,可以针对特定事件向用户发送自动回复。我想使用 Redis 来存储谁收到了什么事件。

基本上,在 ruby​​ 中,数据结构可能看起来像这样,其中您有一个用户到事件的映射以及每个事件的发送日期。

{
  "mary@example.com" => {
    "sent_comment_reply" => ["12/12/2014", "3/6/2015"],
    "added_post_reply" => ["1/4/2006", "7/1/2016"]
  }
}

在 Redis 数据结构中表示此内容的最佳方式是什么,这样您就可以问,Mary 是否收到了 sent_comment_reply?如果有,最近一次是什么时候?

简而言之,问题是,如何(如果可能的话)在 Redis 中拥有一个包含数组的哈希结构。

与使用带有复合键的集合或列表相反的基本原理是散列具有 O(1) 查找时间,而查找列表 (lrange) 和集合 (smembers) 将是 O(s+n) 和集合分别为 O(n)。

最佳答案

在 Redis 中构建它的一种方式,取决于您知道用户的事件并且您希望最新的在内存中是新鲜的:

  1. 每个用户的排序集。排序集的内容将是事件代码; sent_comment_reply, added_post_reply 以最新事件的评分最高者为准。您可以使用 ZRANK 来获得问题的答案:

    Mary 收到 sent_comment_reply 了吗?

  2. 用户的散列,这次你将字段作为事件sent_comment_reply,值是它的内容,应该用最新的值更新,包括正文、日期等。这将回答问题:

    如果有,最近一次是什么时候?

备注:Sorted sets are really fast ,在此示例中,我们将事件作为数据。

With sorted sets you can add, remove, or update elements in a very fast way (in a time proportional to the logarithm of the number of elements). Since elements are taken in order and not ordered afterwards, you can also get ranges by score or by rank (position) in a very fast way. Accessing the middle of a sorted set is also very fast, so you can use Sorted Sets as a smart list of non repeating elements where you can quickly access everything you need: elements in order, fast existence test, fast access to elements in the middle!

关于ruby - 使用redis存储结构化事件日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34885990/

相关文章:

c - 如何在C中使用结构体中的指针

amazon-web-services - Sidekiq 统计数据神秘重置

ruby-on-rails - 生成带参数的链接路径

javascript - 如何将 Rails 数据传递给 JS 或 Coffeescript?

python - 多键多值非确定性 python 字典

data-structures - 功能数据结构中的简单 "undo"

docker - 在docker上本地访问redis——docker compose

asp-classic - 经典ASP下的Redis(VBScript)

ruby-on-rails - 单元测试需要 attr_accessor,但会阻止字段被写入

ruby-on-rails - ruby rails : How do I sum up these elements in my database?