0

I am using redis sorted sets to save user notifications. But as i never did a notification system, I am asking about my logic.

I need to save 4 things for each notification.

  • post_id
  • post_type - A/B
  • visible - Y/N
  • checked - Y/N

My question is how can I store this type of structure in sorted sets?

ZADD users_notifications:1 10 1_A_Y_Y 
ZADD users_notifications:1 20 2_A_Y_N
....

There is a better way to do this type of stuff in redis? In the case above i am saving the four thing in each element, and i need to split by the underscore in the server language.

anvd
  • 3,997
  • 19
  • 65
  • 126

1 Answers1

7

It really depends on how you need to query the data.

The most common way to approach this problem is to use a sorted set for the order and a hash for each object.

So:

ZADD notifications:<user-id> <timestamp> <post-id>
HMSET notifications:<user-id>:<post-id> type <type> visible <visible> checked <checked>

You'd use ZRANGE to get the latest notifications in order and then a pipelined call to HMGET to get the attributes for each object.

As I mentioned, it depends on how you need to access the data. If, for example, you always show visible and unchecked notifications to a user, then you probably want to store those IDs in a different sorted set, so that you don't have to query for the status.

Assuming you have such a sorted set, when a user dismisses a notification you'd do:

HSET notifications:<user-id>:<post-id> visible 0
ZREM notifications:<user-id>:visible <post-id>
djanowski
  • 5,610
  • 1
  • 27
  • 17
  • can we combine zadd and hmset into lua instead of bundling it as a transaction, would that perform any better? – PirateApp May 09 '18 at 11:17