Micku
Micku

Reputation: 550

How to verify a value is exist in list in redis?

I am using redis List for storing a list of users. I want to check whether a user is present in that list.

eg: my list is

 user: {name1,name2,name3}

I want to check whether name3 is present in list. How is it possible using redis?

Upvotes: 1

Views: 8227

Answers (3)

Not_a_Golfer
Not_a_Golfer

Reputation: 49177

To add to what's been said, if you'd at any point like to sort the users somehow, you're actually better off using a sorted set, where each element has a score, and you can page on ranges like a list, but access is nearly O(1)

Upvotes: 1

Linus Thiel
Linus Thiel

Reputation: 39223

Redis lists are probably not the best data structure if you need to check for membership. As msgmash.com says, sets are better for this purpose, and if it's a user list I'm guessing that each element will be unique? In that case, a set is what you want.

If you need a list for any reason, the only way (apart from fetching the whole list and iterating over it, which is suboptimal) is to either LINSERT a new value before or after the value you're checking for - it will return -1 if value does not exist. However, if the value exists you will need to remove the element you just inserted. You can also use LREM in a similar manner.

But again, you're probably better off with a set for this.

As always, I recommend you read through the documentation for Redis commands -- it's very good and clear documentation.

Upvotes: 4

msgmash.com
msgmash.com

Reputation: 1035

If you store the values as sets, then you can check for set membership. The phpredis page https://github.com/nicolasff/phpredis has examples of the sAdd command (add an item to a set for a given key) and sIsMember command (check if a value is a member of a set for a given key).

Otherwise, you'll have to do the membership check in PHP after getting the whole value back from redis and exploding it.

Upvotes: 2

Related Questions