Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update element in Redis stored in sorted set?

I use Redis as persistence of my data in sorted set. My data looks like the following:

{text: 'Some text1', data: [1, 2, 3]},
{test: 'Some text2', data: [1, 3]}
.
.
.

How to update some element in that list? Let's say I need update

{test: 'Some text2', data: [1, 3]}

to

{test: 'Some text2', data: [1, 3, 7]}
like image 448
Erik Avatar asked Sep 19 '25 01:09

Erik


1 Answers

You can only add values to sorted set, or remove them. You cannot change/update them, except their score.

You can instead save values directly as strings:

SET text2 "{\"test\": \"Some text2\", data: [1, 3]}"

And then update them by replacing the original value

SET text2 "{\"test\": \"Some text2\", data: [1, 3, 7]}"

Other option is to store the values in Hash.

UPDATE:

Suppose you have User objects which are persisted as json with key "users:[id]":

SET users:1 "{\"id\":1,\"name\":\"Santtu\"}"

Then store the keys of user objects in sorted set "users".

ZADD users 1 "users:1"
ZADD users 2 "users:2"

You can now get the users by first querying for the keys and then for each user data:

ZRANGE users 0 9 # returns [ "users:1", "users:2", ...]
GET "users:1"
GET "users:2"
...

Change the order of users in set by changing the scores:

ZADD users 2 "users:123"
ZADD users 1 "users:456"
like image 88
santervo Avatar answered Sep 20 '25 16:09

santervo