Unique value in redis list/set

Instead of using a list, use a set. Sets are containers for unique objects. Each object can only appear once in a set. Take a look at the set-related commands here: http://redis.io/commands/#set.

And an example using redis-cli (we attempt to add "Product One" twice, but it only appears once in the list of products):

$ redis-cli
127.0.0.1:6379> sadd products "Product One"
(integer) 1
127.0.0.1:6379> sadd products "Product Two"
(integer) 1
127.0.0.1:6379> sadd products "Product Three"
(integer) 1
127.0.0.1:6379> sadd products "Product One"
(integer) 0
127.0.0.1:6379> smembers products
1) "Product Three"
2) "Product One"
3) "Product Two"
127.0.0.1:6379>

Why not just call Redis.lrem before? So if it finds any occurences of the item, removes them, otherwise will do nothing. Something like this:

def push_item_to_the_list(LIST_KEY, item)
   Redis.lrem(LIST_KEY, 0, item)
   Redis.lpush(LIST_KEY, item)
end

Tags:

Nosql

Redis