Happydevdays
Happydevdays

Reputation: 2082

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.

Upvotes: 3

Views: 2253

Answers (1)

Karthikeyan Gopall
Karthikeyan Gopall

Reputation: 5699

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.

Upvotes: 1

Related Questions