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

查看:56
本文介绍了在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'.

如果可以,你会怎么做?

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.

我目前正在使用 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 中使用 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.

Lets push a few values to a 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天全站免登陆