Redis:如何按键对哈希进行排序? [英] 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
...
我想用这样的 KEYS 命令检索所有密钥:
I want to retrieve all the keys with the KEYS command like that :
KEYS news:*
键没有排序的问题:
news:3
news:1
news:2
我想以正确的顺序检索密钥列表.我不确定哈希是我需要的结构.但是,根据 redis 文档:
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 documentation :
Redis Hashes 是字符串字段和字符串值之间的映射,因此它们是表示对象的完美数据类型(例如,具有姓名、姓氏、年龄等多个字段的用户):
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.
有什么建议吗?
推荐答案
将 Redis 哈希视为索引文档.
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 ...
..
在上面,news:1
是散列键",后跟一个散列字段",最后是它的关联值.
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'.
使用 MULTI/EXEC
构造来设置新闻项(有 n 个字段)的所有字段,最后还添加哈希键——例如你的新闻项目——它是一个排序集.或者,您可以将它们添加到列表中,然后在该列表上使用 SORT
命令.
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.
这篇关于Redis:如何按键对哈希进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!