Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for a copy set command (or alternative) in Redis

Tags:

I'm a newcomer to Redis and I'm looking for some specific help around sets. To give some background: I'm building a web-app which consists of a large number of card decks which each have a set of individual cards with unique ids. I want users to have a set of 5 cards drawn for them at random from a specific deck.

My plan is to have all of the card ids of a given deck stored as a set in Redis; then I want to use the SPOP function to draw individual cards and remove them from the set so that they are not drawn again within that hand. It would seem to make sense to do this by copying the deck's 'master set' of card IDs into a new temporary set, performing the popping on the copy and then deleting the copied set when I'm done.

But: I can't find any Redis function to command a set copy - the closest thing I can see would be to also create an empty set and then 'join' the empty set and the 'master copy' of the set into a new (if temporary) set with SUNIONSTORE, but that seems hacky. I suppose an alternative would be to copy the set items out into my 'host language' (node.js) and then manually insert the items back into a new Redis set, but this also seems clunky. There's probably a better third option that I haven't even thought of.

Am I doing something wrong - am I not 'getting' Redis, or is the command-set still a bit immature?

like image 978
Alex Dean Avatar asked Dec 17 '10 21:12

Alex Dean


People also ask

Which one is LIST command in Redis?

Redis reads lists from left to right, and you can add new list elements to the head of a list (the “left” end) with the lpush command or the tail (the “right” end) with rpush . You can also use lpush or rpush to create a new list: lpush key value.

What is set in Redis?

Redis sets are unordered collections of unique strings that act like the sets from your favorite programming language (for example, Java HashSets, Python sets, and so on). With a Redis set, you can add, remove, and test for existence O(1) time (in other words, regardless of the number of set elements).

Which command is used to return the number of elements in a set in Redis?

The SCARD command returns the cardinality (i.e. number of items) of a Redis set.


1 Answers

redis> sadd mydeck 1 (integer) 1 redis> sadd mydeck 2 (integer) 1 redis> sadd mydeck 3 (integer) 1 redis> smembers mydeck 1) "1" 2) "2" 3) "3" redis> sunionstore tempdeck mydeck (integer) 3 redis> smembers mydeck 1) "1" 2) "2" 3) "3" redis> smembers tempdeck 1) "1" 2) "2" 3) "3" 

Have fun with Redis! Salvatore

like image 84
antirez Avatar answered Sep 19 '22 21:09

antirez