Question

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.

Was it helpful?

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.

OTHER TIPS

Sorry guys, this is the problem specific to Rails.

I have installed redis gem version 2.2.2 and it didnt have support for deleting multiple keys. But however entering to redis-cli for redis server >=2.4 we we can achieve it.

gagan@gagan-desktop:~/projects/test_proj [master]$ redis-cli
redis 127.0.0.1:6379> smembers "college"
1) "champion1"
2) "champion2"
3) "champion3"
4) "champion4"
5) "champion5"
redis 127.0.0.1:6379> srem "college" "champion1" "champion2"
(integer) 2
redis 127.0.0.1:6379> smembers "college"
1) "champion3"
2) "champion4"
3) "champion5"
redis 127.0.0.1:6379> exit
% telnet localhost 6379
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

...

sadd myset 1 2 3      
:3
srem myset 1 3
:2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top