Ander2
Ander2

Reputation: 5658

Is there a way to return a sorted key list from a hash?

I'm new to redis and reading the documentation I'm not able to find a solution to my problem.

I have a hash with names and phone numbers and I would like to get the a sorted list of the keys in the hash.

So my hash (phonebook) looks like this:

 Andrew -> 9999
 Sam    -> 6666
 Eddy   -> 5555

If I run hkeys phonebook I get this (keys are returned as they are stored):

 Andrew
 Sam
 Eddy

And I would like to get this (ordered keys):

 Andrew
 Eddy
 Sam

How could I archive this? Am I using the correct data structure?

Upvotes: 2

Views: 242

Answers (1)

raffian
raffian

Reputation: 32056

You can use a sorted set to achieve this, not a hash, and you don't need to maintain a parallel list; it's all contained in a single structure...

Populate the sorted set...

> zadd ss:phonebook 9999 Andrew
> zadd ss:phonebook 4444 Sam
> zadd ss:phonebook 3333 Bob
> zadd ss:phonebook 7777 Maria
> zadd ss:phonebook 8888 Sophia

Since ss:phonebook contains string values (the names), and you want to sort them lexicographically, use the ALPHA modifier:

> SORT ss:phonebook ALPHA
1) "Andrew"
2) "Bob"
3) "Maria"
4) "Sam"
5) "Sophia"

Hope it helps...

Upvotes: 2

Related Questions