Redis : How can I sort my hash by keys?

前端 未结 2 1584
孤街浪徒
孤街浪徒 2020-12-30 15:09

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

相关标签:
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
    
    0 讨论(0)
  • 2020-12-30 16:05

    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.

    0 讨论(0)
提交回复
热议问题