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.
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:
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):
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 withindex
, 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.