Redis Booksleeve, temporary set

387 views Asked by At

I need to do an Except operation between an existing set and some values coming as input from a user. How can I do this inte best way? I was first thinking about using a temporary set where I store the values from the user. Will that work in a multithreaded application (web)? If so, how can I be sure the temporary set is not overwritten by other users between before I do the Except call? Or do I need a unique set temporary set for each user?

Maybe transactions are the way to go? http://redis.io/topics/transactions

1

There are 1 answers

1
Eli On

Set except is the same as set difference. In Redis, we call this operation set difference, and we can do it using either the SDIFF command, or the SDIFFSTORE command, depending on whether we want to just return the result, or store it in a new set. These are both built in functions.

In your case, since one of your sets is user generated, just encapsulate the whole thing in a pipeline. This will run the whole operation as one atomic transaction that will not allow any other operations against Redis until it finishes (due to Redis' single threaded nature). This would look something like (using Python and Redis-py as an example language):

pipe = redis.pipeline()
pipe.sadd('user_set', 'user_val1', 'user_val2', 'user_valn')
diff_result = pipe.sdiff('my_set', 'user_set')
pipe.del('user_set')
pipe.execute()
#do whatever with diff_result here.