I have a redis list I have created, I am using it as a queue at the moment that reverses once in a while. My problem is that I would like to be able to get the index of an item on that queue/list by value.
Example
If I have a list with the following values:
{"dan","eduardo","pedro"}
The indexes would be:
0 : "dan"
1 : "eduardo"
2 : "pedro"
I want to be able by passing in the value to get the index of that value on my list.
Like "eduardo" and get back '1'.
Is that possible if so how would you do it?
Also something I should say is that I am performing queue commands to my list, removing items from the top and adding them at the bottom.
I am currently using node.js 0.6.6 and the latest redis module with the latest redis version 2.4.4.
I am happy for a solution just in redis-cli.
Also there is no constraint other then it must be possible to do it with redis alone, no external process etc however if you want to use the EVAL command with lua go for it.
Edit
Also I think my answer might be on sorted sets not queues.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With