Skip to content

Instantly share code, notes, and snippets.

@psobot
Created October 1, 2013 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psobot/6778936 to your computer and use it in GitHub Desktop.
Save psobot/6778936 to your computer and use it in GitHub Desktop.
Atomic Redis INCRBY on a specific field of all JSON-encoded elements of a Redis list.
-- Let's say you've got a Redis list that's composed of JSON values:
-- -- {"a": 5.2, "b": "something blah blah"}
-- -- {"a": 4.3, "b": "something blah blah"}
-- -- {"a": 125.2, "b": "something blah blah"}
-- And let's say that you want to increment all of the "a" fields by n.
-- Call the below script with:
-- -- KEYS = [key_of_list_to_update]
-- -- ARGV = [json_key_to_incr, value_to_add]
local num = redis.call('llen', KEYS[1])
for i = 1,num do
local obj = cjson.decode(redis.call('lpop', KEYS[1]))
obj[ARGV[1]] = obj[ARGV[1]] + ARGV[2]
redis.call('rpush', KEYS[1], cjson.encode(obj))
end
return num
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment