Created
October 1, 2013 14:03
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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