Checking if a value exists in a list already Redis
I am surprised that no one mentioned the set, which perfectly solved the question.
Using the sismember key value in set, it checks if the value is a member of the key.
Here is the example:
redis 127.0.0.1:6379> SADD myset1 "hello"
(integer) 1
redis 127.0.0.1:6379> SISMEMBER myset1 "hello"
(integer) 1
redis 127.0.0.1:6379> SISMEMBER myset1 "world"
(integer) 0
Your options are as follows:
- Using
LREM
and replacing it if it was found. - Maintaining a separate
SET
in conjunction with yourLIST
- Looping through the
LIST
until you find the item or reach the end.
Redis lists are implemented as a http://en.wikipedia.org/wiki/Linked_list, hence the limitations.
I think your best option is maintaining a duplicate SET
. This is what I tend to do. Just think of it as an extra index. Regardless, make sure your actions are atomic with MULTI
-EXEC
or Lua scripts.
You can also use LPOS
.
When the item exists it returns a number indicating the position:
LPOS mylist myitem
3
When not it returns nill
:
LPOS mylist myitem_which_do_not_exits
(nil)
Notes:
- Available since 6.0.6.
- Time complexity: O(N)
- https://redis.io/commands/lpos
Lists allow duplicates but do not provide a simple way to check for existence and as @Fritzy advised, you either need to:
- Make multiple operations (remove then add again if found during removal) for simple checks = Cost in time
- Maintain a separate set = Cost in memory
I am surprised no one advised you to use either a Hash Table or a Sorted Set which combine advantages of allowing duplicity (by storing the number of elements as value - Hash Table, or score - Sorted Set) and indexing members by nature of a hash table/set.
Hash Table
To check for a key existence, use HEXISTS
for a specific field which returns 0
if the specified member does not exist.
You could also use the HGET
command. It returns a nil
answer if the specified member does not exist.
To add a new member, simply use HINCRBY
which will either update the value (ie the number of elements with the member name) or create a new member if it does not exist.
Sorted Set
To check for a key existence, use either one of the three following commands:
ZSCORE
ZRANK
ZREVRANK
They return a nil
answer if the specified member does not exist.
To add a new member, simply use ZINCRBY
which will either update the score (ie the number of elements with the member name) or create a new member if it does not exist.
To sum up: Sorted Sets or Hash Tables allow you to make all the operations with your requirements with a single command.