如何做"GROUP BY"在Redis中 [英] How to do "GROUP BY" in Redis

查看:63
本文介绍了如何做"GROUP BY"在Redis中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种解决方案,该方法是如何从具有相同值的 HASH 中获取所有字段.

I'm try to find a solution, of how to get all the fields from a HASH that has the same values.

例如

redis > HSET my_hash "foo" 1
(integer) 1
redis > HSET my_hash "bar" 1
(integer) 1
redis > HSET my_hash "baz" 0
(integer) 1
redis > HGETALL my_hash
1) "foo"
2) "1"
3) "bar"
4) "1"
5) "baz"
6) "0"

所以我想要做的事情是 HGETALL my_hash"WHERE VALUE = 1" .预期结果将是 foo bar .如果有人可以指示我如何使用本机命令或使用 Lua 做到这一点,那就太好了.

So what I want is to do something like HGETALL my_hash "WHERE VALUE = 1". And expected result would be foo and bar. If someone could point me on how to do this using native commands or using Lua would be awesome.

谢谢.

推荐答案

您可以这样做

在名为 script.lua 的 lua 脚本中

in a lua script named script.lua

local hash_val = redis.call('hgetall',KEYS[1])
local result = {}
for i = 0 , #hash_val do
    if hash_val[i] == ARGV[1] then
        table.insert(result,hash_val[i-1])
        table.insert(result,hash_val[i])
    end
end
return result

lua通过序列key0,val0,key1,val1等获取哈希值...

lua get hash by sequence key0,val0,key1,val1, etc...

,然后您可以这样称呼它:

and after you can call it that's way:

redis-cli  eval "$(cat script.lua)" 1 "my_hash" 1

您将拥有:

1) "foo"
2) "1"
3) "bar"
4) "1"

有关评估功能的更多信息,此处

more information for the eval function here

edit:如注释中的deltheil所述,仅检查值并且不进行不必要的检查,您可以将for循环加2,因为散列请求的呈现是键,值,键,值等...:

edit : as said deltheil in comment , for check only the values and don't make unecessary check you can step the for loop by 2 because the rendering of a hash request is key,values,key,value,etc...:

local hash_val = redis.call('hgetall',KEYS[1])
local result = {}
for i = 2 , #hash_val, 2 do
    if hash_val[i] == ARGV[1] then
        table.insert(result,hash_val[i-1])
        table.insert(result,hash_val[i])
    end
end
return result

这篇关于如何做"GROUP BY"在Redis中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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