通过Redis列表中的值获取项目的索引 [英] Get the index of an item by value in a redis list

查看:118
本文介绍了通过Redis列表中的值获取项目的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个已创建的Redis列表,暂时将其用作队列,但有时会反向.我的问题是我希望能够按值获取该队列/列表上某个项目的索引.

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.

示例

如果我有一个包含以下值的列表:

If I have a list with the following values:

{"dan","eduardo","pedro"}

索引为:

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.

就像"eduardo",然后取回"1".

Like "eduardo" and get back '1'.

有可能吗?

我还应该说的是,我正在对列表执行队列命令,从顶部删除项目,然后在底部添加项目.

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.

我当前正在使用node.js 0.6.6和最新的redis模块以及最新的redis版本2.4.4.

I am currently using node.js 0.6.6 and the latest redis module with the latest redis version 2.4.4.

我很高兴能在redis-cli中找到解决方案.

I am happy for a solution just in redis-cli.

除此之外,没有其他限制,那么必须可以单独使用redis进行操作,而无需外部进程进行处理,但是如果您想通过lua go使用EVAL命令,就可以这样做.

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.

编辑

我还认为我的答案可能是在排序的集合上,而不是在队列上.

Also I think my answer might be on sorted sets not queues.

推荐答案

我不知道它的nodejs客户端详细信息,但是以下是lua中非常简单的indexOf命令的实现.

I don't know the nodejs client details for this, but the following is an implementation of a very simple indexOf command in lua.

在我的文件indexof.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

让一些值推送到mylist.

> rpush mylist foo bar baz qux
(integer) 4

我们可以使用lua脚本在列表中找到任何值的索引.命令是O(N).

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

bar的索引为1

> lindex mylist 1
"bar"

nil的索引是-1

$ redis-cli --eval indexof.lua mylist , nil
(integer) -1

请参阅 http://redis.io/commands/eval 有关EVAL命令的更多文档.

Look at the http://redis.io/commands/eval further documentation on EVAL command.

这篇关于通过Redis列表中的值获取项目的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆