0

I'm coding an IM system.

I'm using Redis and JSON to store the data. I have a Redis Set with the conversation IDs. When I retrieve them, I would like to get the list sorted by the timestamp of the messages:

conversation 9  -> last message timestamp: 1390300000
conversation 12 -> last message timestamp: 1390200000
conversation 7  -> last message timestamp: 1390100000

I have a Set with the conversations where each user participates (user1337:conversations) and a List with the JSON-encoded messages of each conversation (conversation1234:messages).

I guess there is no need for tricks, so it can be done natively with Redis. How would you manage to achieve this?

Oriol del Rio
  • 699
  • 7
  • 16

1 Answers1

1

Sounds like a Sorted Set is exactly what you need.

You would set the timestamp of each conversation as its score (see ZADD) and then you can retrieve them ordered, using commands like ZRANGE, ZRANGEBYSCORE, ZREVRANGE and ZREVRANGEBYSCORE.

Agis
  • 32,639
  • 3
  • 73
  • 81
  • Thank you very much. I tried Sorted Sets before, but I didn't catch on setting the timestamp directly. – Oriol del Rio Jan 21 '14 at 09:59
  • @OrioldelRio Sounds like the perfect case for a sorted set and it's great that Redis has them built-in :) – Agis Jan 21 '14 at 10:00