Redis : How can I sort my hash by keys?
Suppose that I have some news stored in a hash. I have different hashes (each hash represent one news) :
news:1
news:2
news:3
...
I want to retrieve all the keys with the KEYS command like that :
KEYS news:*
The problem the keys are not sorted :
news:3
news:1
news:2
I would like to retrieve the list of keys in the right order. I'm not sure that the hash is the structure that I need. But, according to the redis docum开发者_JAVA百科entation :
Redis Hashes are maps between string field and string values, so they are the perfect data type to represent objects (for instance Users with a number of fields like name, surname, age, and so forth):
Storing my news object in a hash seems to be a good idea.
Any suggestions ?
Think of Redis hashes as indexed documents.
HSET news:1 title levy_breaks
HSET news:1 type breaking_news
HSET news:1 byline alphazero
HSET news:1 date 04:25:2011
HSET news:1 content <the story>
HSET news:2 ...
..
In the above, news:1
is the 'hash key', followed by a 'hash field' and finally its associated value.
That said, it seems you simply want to sort your 'hash keys'.
Use a MULTI/EXEC
construct to set all the fields for a news item (which has n fields), and finally also add the hash key -- e.g. your news item -- it to a sorted set. Alternatively, you can just add them to a list and use the SORT
command on that list.
The Redis docs.
What you can do is store a set or list of the news items that exist. For example, when you create a new news item, let's say news:4
, you could add the index 4 to a set, say list:news
, which would now have [1, 2, 3, 4]
.
Now suppose your news hash structure is date, author. With this in place you could execute the following:
sort list:news get *->some_value_a ->*->some_value_b
精彩评论