get inserted key in redis

2019-06-01 05:45发布

问题:

I am using this code:

sadd my_set "el1"

to insert "el1" into my_set. sadd only returns the number of inserted elements. What I need is the key of the inserted element so I can retrieve it later. I am sure there is a way that I am not aware of. Is sadd the right function or I should choose something else like set/get?

EDIT: I need something like auto_increment key in mysql. When I insert something, get the last inserted element for further use.

I need something like this:

key: 1
value: {"name": "jack", "tel": "12412415"}

so I could get the array using key = 1.

回答1:

To do something vaguely similar to "auto_increment," I would look at the INCR function:

http://redis.io/commands/incr

It will increment a value, returning the new value to you - and it is atomic (like most/all Redis commands), so you don't need to worry about threading issues. So your steps would be something like:

  1. SET an increment key.
  2. When you want to add a value, INCR the key, and SET your new value using the value INCR returned.
  3. INCR has at this point increased the value of the increment key, so any repeated value insertions will use the "next" number.

If you want to store a list of items which can be looked up by index, you probably want to do something like this (in programming pseudocode):

// When you initialize your database for the first time.
SET index "0"

// When you want to insert a new item:
INCR index
SET myList:(index value) "My Value"

// When you want to retrieve an item, and you have the index for it:
GET myList:(index value)

In this example, I'm assuming that in your program you are keeping track of the values returned by INCR. The value INCR returns is going to be the index at which you insert the new item, as well as the index with which you'll look up your item later. So, in my example code, replace (index value) with the stored value you got back from INCR (how you do this depends on what programming language you're using, of course).

Note that this DOES allow deletion of items in the middle, via DEL myList:(index value), because you're tracking the last index with index, so even if an item is deleted, the last index will still remain the same - this behaves very similarly to "auto increment" fields in most SQL servers.

You really don't want to use sets for this; sets are inherently unordered, and they are not really made to look things up by "key" - items in a set don't even really have a key. Sets are more useful for the other set operations you can perform on them, like SINTER or SDIFF.



标签: insert redis