fege
fege

Reputation: 567

How can I sort hset in Redis?

I would to sort my data with point

redis 127.0.0.1:6379[4]> hset player1 point 2
(integer) 1
redis 127.0.0.1:6379[4]> hset player1 level 5
(integer) 1
redis 127.0.0.1:6379[4]> hset player2 point 1 
(integer) 1
redis 127.0.0.1:6379[4]> hset player2 level 9
(integer) 1
redis 127.0.0.1:6379[4]> hset player3 point 10
(integer) 1
redis 127.0.0.1:6379[4]> hset player3 level 5
(integer) 1

Is there a way that return me a list in what way?

player3
player1
player2

Upvotes: 0

Views: 1676

Answers (1)

Leonid Beschastny
Leonid Beschastny

Reputation: 51450

You cant sort HSET response in redis. But you can use Redis sorted set instead of a hashmap:

ZADD players 2 player1
ZADD players 1 player2
ZADD players 10 player3

Now you can sort all your players by score:

ZREVRANGE players 0 -1

You can use both HGET and ZREVRANGE if you want to store additional data. So, you'll use ZREVRANGE to get the keys of best players and GET, HGET or HGETALL to get any additional data you need. But in this case you'll need to maintain both sorted set and hashmap:

HMSET player1 name Peter level 5
HMSET player2 name John level 9
HMSET player3 name Michael level 5
ZADD players 2 player1 1 player2 10 player3

Upvotes: 1

Related Questions