Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a value to a Redis list only if it doesn't already exist in the list?

Tags:

redis

I'm trying to add a value to a list but only if it hasn't been added yet.

Is there a command to do this or is there a way to test for the existence of a value within a list?

Thanks!

like image 850
boom Avatar asked May 18 '13 06:05

boom


2 Answers

I need to do the same. I think about to remove the element from the list and then add it again. If the element is not in the list, redis will return 0, so there is no error

lrem mylist 0 myitem
rpush mylist myitem 
like image 141
0xAffe Avatar answered Nov 03 '22 09:11

0xAffe


As Tommaso Barbugli mentioned you should use a set instead a list if you need only unique values. see REDIS documentation SADD

redis>  SADD myset "Hello"
(integer) 1
redis>  SADD myset "World"
(integer) 1
redis>  SADD myset "World"
(integer) 0
redis>  SMEMBERS myset
1) "World"
2) "Hello"

If you want to check the presence of a value in the set you may use SISMEMBER

redis>  SADD myset "one"
(integer) 1
redis>  SISMEMBER myset "one"
(integer) 1
redis>  SISMEMBER myset "two"
(integer) 0
like image 34
mjoschko Avatar answered Nov 03 '22 11:11

mjoschko