Edmon
Edmon

Reputation: 4872

Aggregating values on Redis

I am using Redis to track number of access of events per room, per building, and I need to display these in such a hierarchy. One can look at all events per rooms, but also zoom out and get an aggregate of the event per building.

Each building has unique name, e.g. PRH and each room in the building has a unique number e.g. 101, 212.

Would someone please advise on the schema and best method to store access events and to aggregate them on Redis.

For example, my hierarchy is PRH:101:5, PRH:212:6 and I would like to be able to efficiently show: 101 (5), 212 (6) and PRH (11).

Upvotes: 2

Views: 1246

Answers (1)

Tw Bert
Tw Bert

Reputation: 3809

I'm going to split my answer in two parts, because some new Redis functionality is about to be released, but not in the stable yet.

Redis 2.8.8 and earlier

Use the Hash Set redis datatype, and HINCRBY and HGET

When incrementing a counter, do:

HINCRBY building PRH 1
HINCRBY room:PRH 101 1
# The hash set nor the member doesn't have to exist beforehand.
# If you need atomicity, bundle these commands in a Lua script. Parameterized, avoid Lua SHA1 changes to minimize Lua server-side mem usage.
# Alternative for atomicity: use MULTI+EXEC

After a few increments, you can query on both levels:

HGET building PRH 
# this gives you after 10 increments: PRH=10


HGET room:PRH 101
# this gives you after 5 increments to this room: PRH:101=5

Redis 2.9.x (future)

If the numbers are big, and it's about estimates, plus a standard error of 0.81% is acceptable, you could use the highly efficient HYPERLOGLOG structure/algorithm. See PFCOUNT .

If you want to use ranges combined with lexicographical sorting/querying, look into ZRANGEBYLEX

Hope this helps, TW

Upvotes: 2

Related Questions