Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique value in redis list/set

Tags:

redis

nosql

I want to make a list of existing products in redis but I want to check if the product name already exists first (duplicate checking).

My list currently accepts duplicates, so: Can anyone help me to show how to add unique value in list?

like image 246
Sachin Avatar asked Oct 16 '14 04:10

Sachin


2 Answers

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
like image 21
Simon - ShortPixel Avatar answered Sep 16 '22 12:09

Simon - ShortPixel


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>
like image 174
tobiash Avatar answered Sep 16 '22 12:09

tobiash