Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a redis hash by values in keys

is there a good way in redis to get keys in a hash sorted by values? I've looked at the documentation and haven't found a straightforward way.

Also could someone please explain how sorting is achieved in redis, and what this documentation is trying to say?

I have a very simple hash structure which is something like this:

"salaries" - "employee_1" - "salary_amount"

I'd appreciate a detailed explanation.

like image 860
Deepak Mishra Avatar asked Jul 07 '15 11:07

Deepak Mishra


2 Answers

You can achieve it by sorting a SET by one of your HASH fields. So you should create an indices SET of all of your hashes, and use the BY option. Also, you can use DESC option to get the results sorted from high to low.

e.g.

localhost:6379> sadd indices h1 h2 h3 h4
(integer) 4
localhost:6379> hset h1 score 3
(integer) 1
localhost:6379> hset h2 score 2
(integer) 1
localhost:6379> hset h3 score 5
(integer) 1
localhost:6379> hset h4 score 1
(integer) 1
localhost:6379> sort indices by *->score
1) "h4"
2) "h2"
3) "h1"
4) "h3"
localhost:6379> sort indices by *->score desc
1) "h3"
2) "h1"
3) "h2"
4) "h4"
like image 83
Ofir Luzon Avatar answered Nov 23 '22 19:11

Ofir Luzon


From SORT's documentation page:

Returns or stores the elements contained in the list, set or sorted set at key

So you can't really use it to sort the fields by their values in a Hash data structure. To achieve your goal you should either do the sorting in your application's code after getting the Hash's contents or use a Redis-embedded Lua script for that purpose.

Edit: After speaking with @OfirLuzon we realized that there is another, perhaps even preferable, approach which would be to use a more suitable data structure for this purpose. Instead of storing the salaries in a Hash, you should consider using a Sorted Set in which each member is an employee ID and the score is the relevant salary. This will give you ordering, ranges and paging for "free" :)

like image 25
Itamar Haber Avatar answered Nov 23 '22 18:11

Itamar Haber