Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis : How can I sort my hash by keys?

Tags:

redis

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 ?

like image 790
Sandro Munda Avatar asked Apr 25 '11 16:04

Sandro Munda


People also ask

Can Redis sort?

Sorting in Redis is similar to sorting in other languages: we want to take a sequence of items and order them according to some comparison between elements. SORT allows us to sort LIST s, SET s, and ZSET s according to data in the LIST / SET / ZSET data stored in STRING keys, or even data stored in HASH es.

What does Redis use to sort the elements of a sorted set?

Redis and PHP Redis Sorted Sets are similar to Redis Sets with the unique feature of values stored in a set. The difference is, every member of a Sorted Set is associated with a score, that is used in order to take the sorted set ordered, from the smallest to the greatest score.

What is hash key in Redis?

Redis is an open-source, in-memory key-value data store. A Redis hash is a data type that represents a mapping between a string field and a string value. Hashes can hold many field-value pairs and are designed to not take up much space, making them ideal for representing data objects.

How use Redis hash?

Redis and PHP Redis Hashes are maps between the string fields and the string values. Hence, they are the perfect data type to represent objects. In Redis, every hash can store up to more than 4 billion field-value pairs.


Video Answer


1 Answers

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.

like image 85
alphazero Avatar answered Sep 19 '22 10:09

alphazero