Redis : How can I sort my hash by keys?

懵懂的女人 提交于 2019-11-30 13:35:44

问题


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 documentation :

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 ?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/5780365/redis-how-can-i-sort-my-hash-by-keys

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!