Search code examples
redissetmembers

redis remove particular members from set


I have a set of members. For example a set named "college" with names of 20 colleges.

Now how do I delete only a subset e.g. a selected set of 10 colleges, from the set?

I am running redis server of v2.4.5

The documentation found here http://redis.io/commands/srem said that we can delete multiple keys for redis >= 2.4, but still couldn't figure out how to achieve this.

I am working with RubyonRails and I did it in my rails console

> $redis
    #<Redis client v2.2.2 connected to redis://localhost:6379/0 (Redis v2.4.5)>
> ruby-1.9.3-p0 :011 > $redis.sadd("college","champion1")
 => true 
ruby-1.9.3-p0 :012 > $redis.sadd("college","champion2")
 => true 
ruby-1.9.3-p0 :013 > $redis.sadd("college","champion3")
 => true 
ruby-1.9.3-p0 :014 > $redis.sadd("college","champion4")
 => true 
ruby-1.9.3-p0 :015 > $redis.sadd("college","champion5")
 => true
ruby-1.9.3-p0 :016 > $redis.smembers("college")
 => ["champion1", "champion2", "champion3", "champion4", "champion5"
ruby-1.9.3-p0 :017 > $redis.srem("college","champion1" "champion2")
 => false
ruby-1.9.3-p0 :018 > $redis.smembers("college")
 => ["champion1", "champion2", "champion3", "champion4", "champion5"]

The members "champion1" and "champion2" are not removed from the set.

I have installed redis (2.2.2 ruby) gem.


Solution

  • Given your client library doesn't support the simple way to do it it, you could use sdiff or sdiffstore. Create a set of members to be removed and obtain the difference of the sets, and store the result back into the original set.

    It may be a bit more complex but it should work.