Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the latest set/hash from redis

I'm just getting started with redis and I've hit my first stumbling block with going noSql; previously all I've known is SQL server.

I understand the principle that everything is key value based. But how does that work with ordering, for example:

Using a hash set:

HMSET users:1 firstname 'james' lastname 'smith' created 'datetime.datatime.now'

Now I assume you to add a second record you would get the length of the hash set (in this case we shall say its 1 returned to value x), then add another row:

HMSET users:x firstname 'john' lastname 'smith' created 'datetime.datatime.now'

How would you get the latest record? By date? Or can you just say 'get record at -1 of hashset'?

Possibly I'm proposing to use a hashset when a sorted sets are more appropriate?

like image 325
Jay Avatar asked Oct 27 '11 10:10

Jay


2 Answers

You will want to check the SORT command.

You can sort by create timestamp if that is stored in epoch time.

> HMSET users:1 firstname 'john' lastname 'smith' created 1319729878
"OK"
> HMSET users:2 firstname 'Jane' lastname 'Forbes' created 1319729910
"OK"
> sadd users 1
true
> sadd users 2
true
> sort users get users:*->firstname by users:*->created
["john","Jane"]
> sort users get users:*->firstname by users:*->created desc
["Jane","john"]

You can get multiple keys if you want, SORT is probable the command with most options, study the doc.

About the keys, you have to think carefully about possible key reuse (delete, count+1, insert would reuse the key?), so I just get the keys from relational database in my project.

like image 145
Niloct Avatar answered Oct 07 '22 02:10

Niloct


You should use a sorted set of userids, when you add to the set, add the userid and the the timestamp as the score.

Then you can pull them out in asc or desc order using something like zrevrange, limit this to 1 record to get your latest.

Then you can get all the values from your hash.

like image 43
jmoz Avatar answered Oct 07 '22 00:10

jmoz