Unique value in redis list/set
Solution 1
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>
Solution 2
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
Solution 3
This is my (reckless) solution to keep Redis List unique. (implementation in Ruby)
def push_item_to_the_list(LIST_KEY, item)
insert_status = Redis.linsert(LIST_KEY, 'before', item, item)
if insert_status == -1
Redis.lpush(LIST_KEY, item)
else
Redis.lrem(LIST_KEY, 1, item)
end
end
Each time when you want to push or insert item to your list, check if LINSERT
command will be able to put this item just after the very same item (this is the only way I know to check if the item is already in the redis list or not).
If LINSERT
will return status -1, it means that it was not able to find item in your list - everything is ok (you can push it or insert it now).
If LINSERT
will return other value (size of the list in other case) - it means that it was able to find item already and it was able to insert another item, just after the previous one. It means that you have (at least one) duplication of your item. You can delete one of them now.
Related videos on Youtube
Sachin
Updated on February 27, 2020Comments
-
Sachin over 4 years
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?
-
Itamar Haber over 9 years...and if you need your "list" in order - use a Sorted Set :)
-
adrian over 7 yearsIs there a way to get a queue with unique items in redis? So a sorted set but I want to pop something from the front and then keep popping. :-)
-
Yin over 5 yearsthe position of my item is changed this way.
-
Yin over 5 yearsI need the order