xyzman
xyzman

Reputation: 598

Redis - how to sort by hash field in redis as opposed to key?

Let's suppose I want have redis hash a = {1:10, 2:15, 3:5, 4:0, 5:20}, and a set b = (5,3,4). I want to get a list containing elements from b, sorted by values of a[b] (result in this case is [4,3,5]).

When I try to do this, it doesn't work well.

redis 127.0.0.1:6379> hmset a 1 10 2 15 3 5 4 0 5 20
redis 127.0.0.1:6379> sadd b 5 3 4
redis 127.0.0.1:6379> sort b by a->*
1) "3"
2) "4"
3) "5"

Obviously, asterisk in hash field placeholder doesn't work. Are there other ways beside declaring a:1-a:5 to do this task by means of Redis?

P.S. This is not a duplicate of Redis : How can I sort my hash by keys?, as that question clearly discusses the a:* approach.

Upvotes: 3

Views: 4544

Answers (2)

Jonas Adler
Jonas Adler

Reputation: 913

this is a know issue: link

you could do the following:

redis 127.0.0.1:6379> sadd b 5 3 4

redis 127.0.0.1:6379> zadd a 10 1 15 2 5 3 0 4 20 5

redis 127.0.0.1:6379> zinterstore result 2 a b

redis 127.0.0.1:6379> zrange result 0 -1

1) "4"

2) "3"

3) "5"

Upvotes: 2

Theo
Theo

Reputation: 132972

Maybe you can model it using sorted sets instead? Use the values as score, and the keys as members. Sorted sets are more or less like hashes sorted by value. I'd love to give you an example, but I'm not sure exactly what the problem you're trying to solve is. If you could elaborate maybe I could help.

Upvotes: 0

Related Questions