luna
luna

Reputation: 1

Is there a command in Redis for HASH data structure similar to 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 [key ...]

Available since 1.0.0.

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

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 only brings all fields for one key. I need many keys all fields by key.

Upvotes: 0

Views: 1390

Answers (2)

Malinga
Malinga

Reputation: 515

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.

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.

Option 1 Ex. implementation in pseudo code

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

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

Call the lua sctipt

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

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

Upvotes: 1

Itamar Haber
Itamar Haber

Reputation: 49942

As noted in another answer, there's no built in way but there more workarounds besides a transaction.

Option 1: use a Lua script (i.e. EVAL "..." 3 myhash1 myhash2 myhash3 myfield)

local r = {}
while (#KEYS > 0) do
  local k = table.remove(KEYS,1)
  r[#r+1] = redis.call('HGET', k, ARGV[1])
end

return r

Option 2: write a Redis module

Out of scope as a an answer :)

Upvotes: 0

Related Questions