117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
|
# File 'lib/rhcf/timeseries/redis_strategies.rb', line 117
def register_lua_scripts!(connection)
@lua_script_register ||=
begin
smembers_matching = <<-EOF
local matches = {}
for _, val in ipairs(redis.call('smembers', KEYS[1])) do
if string.match(val, ARGV[1]) then
table.insert(matches, val)
end
end
return matches
EOF
mget_matching_smembers = <<-EOF
local set_key = KEYS[1]
local key_prefix = ARGV[1]
local filter_pattern = ARGV[2]
local limit = tonumber(ARGV[3])
local keys = {}
local keys_to_mget = {}
local function log(msg)
-- redis.call('publish', 'log', msg)
end
local function mget_in_batches(keys_to_mget)
local step = 1024
local results = {}
local last_end = 0
local partial = {}
local function mget_batch(ini , fin)
log("Getting from " .. ini .. ' to ' .. fin .. ' on a total of ' .. #keys_to_mget)
partial = redis.call('MGET', unpack(keys_to_mget, ini, fin))
for _, value in pairs(partial) do table.insert(results, value) end
end
for ending = step, #keys_to_mget, step do
mget_batch(last_end + 1, ending)
last_end = ending
end
if last_end < #keys_to_mget then
mget_batch(last_end + 1, #keys_to_mget)
end
return results;
end
local function sort_and_limit_tuples(subjects, values)
local dictionary = {}
for i, subject in pairs(subjects) do
local value = values[i] or 0
-- redis.call('publish', 'log', subject .. ' += ' .. value)
dictionary[subject] = (dictionary[subject] or 0) + value
end
local tuples = {}
for subject, value in pairs(dictionary) do
-- redis.call('publish', 'log', subject .. ' = ' .. value)
table.insert(tuples, { subject, value } )
end
table.sort(tuples, function(a, b) return b[2] < a[2] end )
local new_subjects = {}
local new_counts = {}
for i, tuple in pairs(tuples) do
if #new_subjects >= limit then break end
local subject = tuple[1]
local value = tuple[2]
table.insert(new_subjects, subject)
table.insert(new_counts, value)
end
return {new_subjects, new_counts}
end
for _, val in ipairs(redis.call('smembers', set_key)) do
if (filter_pattern and string.match(val, filter_pattern)) or not filter_pattern then
table.insert(keys, val)
table.insert(keys_to_mget, key_prefix .. '#{NAMESPACE_SEPARATOR}' .. val)
end
end
if table.getn(keys) > 0 then
local values = mget_in_batches(keys_to_mget)
local sorted = sort_and_limit_tuples(keys, values)
log ("Values card " .. #values .. " | keys card: " .. #keys)
return sorted
else
return {{},{}}
end
EOF
{
mget_matching_smembers: connection.script(:load, mget_matching_smembers),
smembers_matching: connection.script(:load, smembers_matching)
}
end
end
|