jdkealy
jdkealy

Reputation: 4907

How to get the position of an item in a list in redis?

Is there any way if I had a list such as:

rpush "country", "Mexico"
rpush "country", "Morocco"
rpush "country", "M'erica"

Is there any way to see that Morocco is in position 1 of this list?

Upvotes: 4

Views: 1812

Answers (1)

Didier Spezia
Didier Spezia

Reputation: 73236

There is no Redis command to search for a given item in a list, since it would be an O(n) operation. It would not be scalable past a few thousands of items.

Now if you know your lists are small enough, you can implement this operation on client or server side.

On client side:

If you do not care much about the network bandwidth, just get the whole list with "lrange mylist 0 -1" and implement a simple linear search in the client.

On server side:

You can use use Lua server-side scripting to implement a linear search. Here is an example:

eval "local n = redis.call('LLEN', KEYS[1]) - 1
      for i=0,n do
         if redis.call( 'LINDEX', KEYS[1], i ) == ARGV[1] then
             return i
         end
      end
      return -1" 1 mylist item_to_search

This script will return the position of the item in the list (starting at 0), or -1 if the item is not found.

Upvotes: 3

Related Questions