Quantcast
Channel: How to store sorted set of objects in redis? - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Answer by Itamar Haber for How to store sorted set of objects in redis?

$
0
0

Using a single key to store all your hashes will require some serialization as Redis doesn't support nested data structures. The result would be the following:

key: users:pro
         |
         +-----> field       value
                 name:Bruce  "age: 20, score: 100"
                 name:Ed     "age: 22, score: 80"

> HMSET users:pro name:Bruce "age: 20, score: 100" name:Ed "age:22, score:80"

The corresponding Sorted Set would be:

key: users:pro.by_scores
         |
         +---> scores:    80           100
         +---> values: "name:Ed"   "name:Bruce"

> ZADD users:pro.by_scores 80 "name:Ed" 100 "name:Bruce"

Note 1: this approach mandates a unique ID per-user, currently the name property is used which could be problematic.

Note 2: to avoid the serialization (and deserialization), you can consider using a dedicated key per user. That means doing:

key: users:pro:Bruce
         |
         +-----> field       value
                 age         20
                 score       100

key: users:pro:Ed
         |
         +-----> field       value
                 age         22
                 score       80

> HMSET users:pro:Bruce age 20 score 100
> HMSET users:pro:Ed age 22 score 80

key: users:pro.by_scores
         |
         +---> scores:      80                100
         +---> values: "users:pro:Ed"   "users:pro:Bruce"

> ZADD users:pro.by_scores 80 "users:pro:Ed" 100 "users:pro:Bruce"

Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>