Reputation: 6241
I have stored my data in redis hash like this :
client> hmset date:20150513 user 21 m 20 f 1
client> hmset date:20150514 user 17 m 10 f 7
client> hmset date:20150515 user 13 m 3 f 10
client> hmset date:20150516 user 15 m 10 f 5
client> hmset date:20150517 user 15 m 10 f 5
client> hmset date:20150518 user 7 m 3 f 4
client> hmset date:20150519 user 10 m 7 f 3
This is datewise user summary (including male, female bifurcation). Now I want to fetch top 5 keys order by date in descending order. In the above case, I want
date:20150519, date:20150518, date:20150517, date:20150516 and date:20150515.
How do I write script (luascript) or command to retrive data?
Upvotes: 3
Views: 2031
Reputation: 50052
The best way to go about this is to store your dates in a Sorted Set whose score is the date. Your example's data would require something like:
client> ZADD dates 20150515 20150515 20150516 20150516 20150517 20150517 20150518 20150518 20150519 20150519
Now you can easily get the top 5 entries with:
client> ZREVRANGEBYSCORE dates +inf -inf LIMIT 0 5
and follow with an HMGET
for each reply. You could also use SORT
to actually fetch the data, all in one command, i.e.
client> SORT dates GET date:*->user GET date:*->m GET date:*->f LIMIT 0 5 DESC
Lastly, this is of course very doable with Lua, but unless there are additional requirements that you need to address, a script is probably an overkill here.
Upvotes: 3