Redis 中是否有类似于 MGET 的 HASH 数据结构的命令? [英] Is there a command in Redis for HASH data structure similar to MGET?

查看:132
本文介绍了Redis 中是否有类似于 MGET 的 HASH 数据结构的命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一次性调用一组已知 REDIS 哈希键的所有数据字段.我已经将 MGET 用于字符串键,例如:

I need to get in one call all data fields for a set of known REDIS hash keys. I've used MGET for string keys such as :

MGET 键 [key ...]

MGET key [key ...]

自 1.0.0 起可用.

Available since 1.0.0.

时间复杂度:O(N),其中 N 是要检索的键数.

Time complexity: O(N) where N is the number of keys to retrieve.

返回所有指定键的值.对于每个不包含字符串值或不存在的键,都会返回特殊值 nil.因此,操作永远不会失败.

Returns the values of all specified keys. For every key that does not hold a string value or does not exist, the special value nil is returned. Because of this, the operation never fails.

HMGET 只为一个键带来所有字段.我需要一个键所有字段的许多键.

HMGET only brings all fields for one key. I need many keys all fields by key.

推荐答案

没有这样的命令,redis 哈希在哈希中工作,所以 HMGET 在一个哈希中工作并给出该哈希中的所有字段.无法访问多个哈希中的所有字段.

There is no command like that, redis hashes work within the hash, so HMGET work inside one hash and give all the fields in that hash. There is no way to access all the fields in multiple hashes at ones.

但是,您可以在每个散列上使用多个 HMGET 并获取所有字段.您可以通过管道将这些命令一次性执行.

However you can user several HMGET on each hash and get all the fields. you can pipeline these commands to execute in a one go.

选项 1前任.伪代码实现

Pipeline p
List<String> = p.hgetall('key1', fields...); 
List<String> = p.hgetall('key2', fields...);
List<String> = p.hgetall('key3', fields...);
p.exec(); 

选项 2另一种选择是编写一个 LUA 脚本并使用 EVAL 调用它

Option 2 Other option is to write a LUA script and call that using EVAL

local array = {}
local keys = redis.call('KEYS', '<your pattern>')

for _,key in ipairs(keys) do
    local val = redis.call('HGETALL', key)
    array[#array + 1] = val
end

return array

调用lua脚本

redis-cli EVAL "$(cat test.lua)" 0

1) 1) "field1"
   2) "val"
2) 1) "field1"
   2) "val"
   3) "field2"
   4) "val2"

这篇关于Redis 中是否有类似于 MGET 的 HASH 数据结构的命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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