Get the index of an item by value in a redis list

前端 未结 6 1968
臣服心动
臣服心动 2020-12-31 08:32

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 i

6条回答
  •  Happy的楠姐
    2020-12-31 09:16

    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.

提交回复
热议问题