I have created key in redis as follows.
hmset mykey field1 1 field2 2
OK
//checked with command
hgetall mykey
1) "field1"
2) "1"
3) "field2"
4) "2"
result is ok, and working fine. Now I want to increment both value in a single command like
hincrby mykey field1 1 field2 1
is it possible?
No - HINCRBY
does not support this type of use. If your motivation is to ensure the atomicity of the two increments, use MULTI/EXEC
or a server-side Lua script (see the EVAL
command).
Here's how do address the original question to ensure atomicity:
MULTI
HSET mykey field1 1
HSET mykey field2 2
EXEC
For 2nd question (in the comments - "set only if greater then"), the following script should be EVALed with these parameters 1 <keyname> <value>
:
local curr = tonumber(redis.call("GET", KEYS[1]))
if type(curr) == "number" and curr < tonumber(ARGV[1]) then
redis.call("SET", KEYS[1], ARGV[1])
return "OK"
end