I'm wondering if there's a way to check if a key already exists in a redis list?
I can't use a set because I don't want to enforce uniqueness, but I do want to be able to check if the string is actually there.
I'm wondering if there's a way to check if a key already exists in a redis list?
I can't use a set because I don't want to enforce uniqueness, but I do want to be able to check if the string is actually there.
Lists allow duplicates but do not provide a simple way to check for existence and as @Fritzy advised, you either need to:
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 returns0
if the specified member does not exist. You could also use theHGET
command. It returns anil
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.
No, there is no way to check if a redis list contains a given value. See Redis list commands for reference.
I guess you could use
LREM
to (try to) remove the value, and check the return value to see if it was removed. But then you would have to put it back in, and this seems iffy. There is probably some better solution to your problem - what are you trying to accomplish?Your options are as follows:
LREM
and replacing it if it was found.SET
in conjunction with yourLIST
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 withMULTI
-EXEC
or Lua scripts.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: