Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redis how to autogenerate next key number

I'm crash coursing right now in redis, using 'the little redis book'. What's not clear to me is how I can autogenerate key values.

So for example, the book uses this set statement:

 set users:9001 '{"id":9001, "email":"[email protected]"}'

How can i set things up so that the system keeps track of the next available id? In this case... 9002?

I know there is a INCR function... But I don't know how to incorporate both of these functions together.

So for example, let's say i do this using the redis-cli:

 set mykey 1
 set users:mykey '{"id":mykey, "email":"[email protected]"}'

This works on the command line, but I need a way to do this programmatically. I'm thinking I would:

  get mykey
  INCR mykey
  set users:mykey ....

Does this seem right? is there another way to do this? Also how do I programmatically using phpredis?

Thanks.

like image 288
Happydevdays Avatar asked Dec 07 '25 06:12

Happydevdays


1 Answers

Yes, that is the right way to do it. But a small change in your approach, When you do INCR you will get a incremented value returned by redis. you can use it directly in the next command. So it is simply,

var counter = INCR key
set users:counter . . .

So here you start from the index 1. ie, users:1, users:2 and so on.

Hope this is clear.

like image 99
Karthikeyan Gopall Avatar answered Dec 09 '25 18:12

Karthikeyan Gopall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!