Skip to content

Instantly share code, notes, and snippets.

@cybermaxs
Created August 25, 2016 08:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cybermaxs/abab169ba34609c331db1ce577d24d2c to your computer and use it in GitHub Desktop.
Save cybermaxs/abab169ba34609c331db1ce577d24d2c to your computer and use it in GitHub Desktop.
--------------------------------------------------------------------------------
-- Multi HINCRBY via a LUA script
-- Increments a list of fields in a hash stored at key.
-- KEYS : key of the hash
-- ARGS : list of field/increment
-- Note : Because a script is executed in an atomic way, you should always use this script to increment fields values.
-- ex via cli : redis-cli --eval hmincr.lua myhash , 1 10 2 20
--------------------------------------------------------------------------------
-- gets multiple fields from a redis hash as a dictionary
local hmget = function (key, args)
if next(args) == nil then return {} end
local bulk = redis.call('HMGET', key, unpack(args))
local result = {}
for i, v in ipairs(bulk) do result[args[i]] = v end
return result
end
-- sets all fields for a redis hash from a dictionary
local hmset = function (key, dict)
if next(dict) == nil then return nil end
local bulk = {}
for k, v in pairs(dict) do
table.insert(bulk, k)
table.insert(bulk, v)
end
return redis.call('HMSET', key, unpack(bulk))
end
-- script
local fields = {}
local fieldsAndValues = {}
for i=1,#ARGV,2 do
-- list of hash fields to get
table.insert(fields, ARGV[i])
-- dictionary of args
fieldsAndValues[ARGV[i]] = tonumber(ARGV[i + 1])
end
local hfields = hmget(KEYS[1], fields)
for k, v in pairs(fieldsAndValues) do
local current = hfields[k]
-- never returns nil, but it returns a boolean value (false) if no key exists.
if (current==nil or (type(current) == "boolean" and not current)) then
-- init fields
hfields[k]=v
else
-- incre
hfields[k]=v+tonumber(hfields[k])
end
end
-- update the hash
hmset(KEYS[1], hfields)
return #fields
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment