Get the index of an item by value in a redis list
I don't know the nodejs client details for this, but the following is an implementation of a very simple indexOf command in lua.
In a my file indexof.lua
i have the following code:
local key = KEYS[1]
local obj = ARGV[1]
local items = redis.call('lrange', key, 0, -1)
for i=1,#items do
if items[i] == obj then
return i - 1
end
end
return -1
Lets push a few values to a mylist
.
> rpush mylist foo bar baz qux
(integer) 4
We can use the lua script to find the index of any value within the list. The command is O(N).
$ redis-cli --eval indexof.lua mylist , bar
(integer) 1
index of bar
was 1
> lindex mylist 1
"bar"
index of nil
is -1
$ redis-cli --eval indexof.lua mylist , nil
(integer) -1
Look at the http://redis.io/commands/eval further documentation on EVAL command.
Use sorted sets to implement a queue.
Add members and use timestamp as score.
> ZADD queue 1326990501 foo 1326990502 bar 1326990503 baz 1326990504 qux
(integer) 4
You can return members in FIFO and LIFO order by the use of ZRANGE and ZREVRANGE respectively.
FIFO:
> ZRANGE queue 0 0
"foo"
LIFO:
> ZREVRANGE queue 0 0
"qux"
To find the index of a member use ZRANK. ZRANK op is O(log(N))
> ZRANK queue bar
(integer) 1