How to do “GROUP BY” in Redis

2019-06-07 20:36发布

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

For example

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"

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.

Thanks.

标签: lua redis
1条回答
2楼-- · 2019-06-07 21:03

You can do this

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 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

you will have :

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

more information for the eval function here

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
查看更多
登录 后发表回答