04 Apr

Redis Sorted Object Set (Sorted Hashes)

Redis Sorted Object Set (Sorted Hashes)

We all know that best way to store object in Redis is through, Redis hashes. And Redis sorted sets are used to keep a sorted set with a give score for each value. What if we need a sorted set of objects? What we need is a “Sorted set of Objects” . Which Redis does not support by default. We came up with a hybrid, simple data structure that a allows sorted object using Redis Hashes and Redis Sorted-sets.

Use of Redis Hashes

Here we will keep a objects as Redis hash. Think of a simple object with several values as shown below.

This will be saved in the Redis as below

When we need to edit a existing value and add a new value it can be done as below

Getting full map and some selected value

Whole map or items can be deleted

There is some more commands in the Redis hash that can help us in this process

HEXISTS Check for item
HINCRBY Add to integer value
HINCRBYFLOAT Add to float value
HKEYS Return all keys
HLEN Get number of items
HSCAN Iterate items
HSETNX Set item if doesn’t exist
HVALS Return all values

Use of Redis Sorted Sets

As we said above we need to search with time values and in-order searches. This cannot be done alone by Redis hashes. Here we keep a list of all keys in the Redis hashes as a sorted set. This allow us to get all the maps that came after some time stamp. or between two time stamps. Other than that this allows us to search under topics (EX: get all TICKETS after 00000001 time stamp)

Get items under one topic within a given time range

There is some more commands in the Redis hash that can help us in this process

ZCARD Get number of items
ZCOUNT Number of items within score range
ZINCRBY Add to score
ZLEXCOUNT Lexico­gra­phical range count
ZRANGE Get items within rank range
ZLEXRANGE Get items within lexico­gra­phical range
ZRANGEBYSCORE Get items within score range
ZRANK Get item rank
ZREM Remove item(s)
ZREMRANGEBYLEX Remove items within lexico­gra­phical range
ZREMRANGEBYRANK Remove items within rank range
ZREMRANGEBYSCORE Remove items within score range
ZREVRANGE ZRANGE in reverse order
ZREVRANK ZRANK in reverse order
ZSCAN Iterate items
ZSCORE Get item score


Last updated by .

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.