Redis 中按类别、作者和日期分组的计数器

Counter grouped by category, author and date in Redis

我正在实现一个在关系数据库中存储大量数据的系统。

数据可以分类并有作者。

我想获取按日期、类别和作者分组的项目数以及按日期分组的每个类别的所有项目的总和。

系统必须接近实时。

例如(3 个类别,3 位作者,2 个日期)

item1 category1 author1 2015-04-23
item2 category1 author2 2015-04-23
item3 category2 author1 2015-04-23
item4 category1 author1 2015-04-23
item5 category2 author2 2015-04-23
item6 category2 author2 2015-04-24
item7 category3 author1 2015-04-24
item8 category2 author3 2015-04-24
item9 category2 author2 2015-04-24

结果:

2015-04-23:
    category1 author1: 2
    category1 author2: 1
    category1 author3: 0
    category2 author1: 1
    category2 author2: 1
    category2 author3: 0
    category3 author1: 0
    category3 author2: 0
    category3 author3: 0
2015-04-24:
    category1 author1: 0
    category1 author2: 0
    category1 author3: 0
    category2 author1: 0
    category2 author2: 2
    category2 author3: 1
    category3 author1: 1
    category3 author2: 0
    category3 author3: 0

大约有 50 个类别和大约 50 位作者。

如何在 Redis 中对这种行为进行建模?

对每个日期使用哈希,使用类别和作者作为字段名称,并将计数器作为值。

例如,对于第一项:

HINCRBY 20150423 1:1 1
            ^    ^ ^ ^
      date -+    | | +- increment (static)
    category id -+ +- author id

注意:我故意使用较短的标识符来节省 RAM。

要获取每个日期的数据,只需 HSCAN the relevant key (be careful with HGETALL because it may take too much time/RAM depending on the Hash's size). To get all date keys you get either use SCAN从不使用 KEYS)或在另一个数据结构中保留日期索引 (即一组)。