-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathclient.py
522 lines (425 loc) · 16.5 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
import six
import redis
from redis import Redis, RedisError
from redis.client import Pipeline
from redis.client import bool_ok
from redis._compat import (long, nativestr)
from redis.exceptions import DataError
class CMSInfo(object):
width = None
depth = None
count = None
def __init__(self, args):
response = dict(zip(map(nativestr, args[::2]), args[1::2]))
self.width = response['width']
self.depth = response['depth']
self.count = response['count']
class TopKInfo(object):
k = None
width = None
depth = None
decay = None
def __init__(self, args):
response = dict(zip(map(nativestr, args[::2]), args[1::2]))
self.k = response['k']
self.width = response['width']
self.depth = response['depth']
self.decay = response['decay']
def spaceHolder(response):
return response
def parseToList(response):
res = []
for item in response:
if item is not None:
res.append(nativestr(item))
else:
res.append(None)
return res
class Client(Redis): #changed from StrictRedis
"""
This class subclasses redis-py's `Redis` and implements
RedisBloom's commands.
The client allows to interact with RedisBloom and use all of
it's functionality.
Prefix is according to the DS used.
- BF for Bloom Filter
- CF for Cuckoo Filter
- CMS for Count-Min Sketch
- TopK for TopK Data Structure
"""
MODULE_INFO = {
'name': 'RedisBloom',
'ver': '0.1.0'
}
BF_RESERVE = 'BF.RESERVE'
BF_ADD = 'BF.ADD'
BF_MADD = 'BF.MADD'
BF_INSERT = 'BF.INSERT'
BF_EXISTS = 'BF.EXISTS'
BF_MEXISTS = 'BF.MEXISTS'
BF_SCANDUMP = 'BF.SCANDUMP'
BF_LOADCHUNK = 'BF.LOADCHUNK'
CF_RESERVE = 'CF.RESERVE'
CF_ADD = 'CF.ADD'
CF_ADDNX = 'CF.ADDNX'
CF_INSERT = 'CF.INSERT'
CF_INSERTNX = 'CF.INSERTNX'
CF_EXISTS = 'CF.EXISTS'
CF_DEL = 'CF.DEL'
CF_COUNT = 'CF.COUNT'
CF_SCANDUMP = 'CF.SCANDUMP'
CF_LOADDUMP = 'CF.LOADDUMP'
CMS_INITBYDIM = 'CMS.INITBYDIM'
CMS_INITBYPROB = 'CMS.INITBYPROB'
CMS_INCRBY = 'CMS.INCRBY'
CMS_QUERY = 'CMS.QUERY'
CMS_MERGE = 'CMS.MERGE'
CMS_INFO = 'CMS.INFO'
TOPK_RESERVE = 'TOPK.RESERVE'
TOPK_ADD = 'TOPK.ADD'
TOPK_QUERY = 'TOPK.QUERY'
TOPK_COUNT = 'TOPK.COUNT'
TOPK_LIST = 'TOPK.LIST'
TOPK_INFO = 'TOPK.INFO'
def __init__(self, *args, **kwargs):
"""
Creates a new RedisBloom client.
"""
Redis.__init__(self, *args, **kwargs)
# Set the module commands' callbacks
MODULE_CALLBACKS = {
self.BF_RESERVE : bool_ok,
#self.BF_ADD : spaceHolder,
#self.BF_MADD : spaceHolder,
#self.BF_INSERT : spaceHolder,
#self.BF_EXISTS : spaceHolder,
#self.BF_MEXISTS : spaceHolder,
#self.BF_SCANDUMP : spaceHolder,
#self.BF_LOADCHUNK : spaceHolder,
self.CF_RESERVE : bool_ok,
#self.CF_ADD : spaceHolder,
#self.CF_ADDNX : spaceHolder,
#self.CF_INSERT : spaceHolder,
#self.CF_INSERTNX : spaceHolder,
#self.CF_EXISTS : spaceHolder,
#self.CF_DEL : spaceHolder,
#self.CF_COUNT : spaceHolder,
#self.CF_SCANDUMP : spaceHolder,
#self.CF_LOADDUMP : spaceHolder,
self.CMS_INITBYDIM : bool_ok,
self.CMS_INITBYPROB : bool_ok,
#self.CMS_INCRBY : spaceHolder,
#self.CMS_QUERY : spaceHolder,
self.CMS_MERGE : bool_ok,
self.CMS_INFO : CMSInfo,
self.TOPK_RESERVE : bool_ok,
self.TOPK_ADD : parseToList,
#self.TOPK_QUERY : spaceHolder,
#self.TOPK_COUNT : spaceHolder,
self.TOPK_LIST : parseToList,
self.TOPK_INFO : TopKInfo,
}
for k, v in six.iteritems(MODULE_CALLBACKS):
self.set_response_callback(k, v)
@staticmethod
def appendItems(params, items):
params.extend(['ITEMS'])
params += items
@staticmethod
def appendError(params, error):
if error is not None:
params.extend(['ERROR', error])
@staticmethod
def appendCapacity(params, capacity):
if capacity is not None:
params.extend(['CAPACITY', capacity])
@staticmethod
def appendExpansion(params, expansion):
if expansion is not None:
params.extend(['EXPANSION', expansion])
@staticmethod
def appendNoScale(params, noScale):
if noScale is not None:
params.extend(['NONSCALING'])
@staticmethod
def appendWeights(params, weights):
if len(weights) > 0:
params.append('WEIGHTS')
params += weights
@staticmethod
def appendNoCreate(params, noCreate):
if noCreate is not None:
params.extend(['NOCREATE'])
@staticmethod
def appendItemsAndIncrements(params, items, increments):
for i in range(len(items)):
params.append(items[i])
params.append(increments[i])
@staticmethod
def appendMaxIterations(params, max_iterations):
if max_iterations is not None:
params.extend(['MAXITERATIONS', max_iterations])
@staticmethod
def appendBucketSize(params, bucket_size):
if bucket_size is not None:
params.extend(['BUCKETSIZE', bucket_size])
################## Bloom Filter Functions ######################
def bfCreate(self, key, errorRate, capacity, expansion=None, noScale=None):
"""
Creates a new Bloom Filter ``key`` with desired probability of false
positives ``errorRate`` expected entries to be inserted as ``capacity``.
Default expansion value is 2.
By default, filter is auto-scaling.
"""
params = [key, errorRate, capacity]
self.appendExpansion(params, expansion)
self.appendNoScale(params, noScale)
return self.execute_command(self.BF_RESERVE, *params)
def bfAdd(self, key, item):
"""
Adds to a Bloom Filter ``key`` an ``item``.
"""
params = [key, item]
return self.execute_command(self.BF_ADD, *params)
def bfMAdd(self, key, *items):
"""
Adds to a Bloom Filter ``key`` multiple ``items``.
"""
params = [key]
params += items
return self.execute_command(self.BF_MADD, *params)
def bfInsert(self, key, items, capacity=None, error=None, noCreate=None, expansion=None, noScale=None):
"""
Adds to a Bloom Filter ``key`` multiple ``items``. If ``nocreate``
remain ``None`` and ``key does not exist, a new Bloom Filter ``key``
will be created with desired probability of false positives ``errorRate``
and expected entries to be inserted as ``size``.
"""
params = [key]
self.appendCapacity(params, capacity)
self.appendError(params, error)
self.appendNoCreate(params, noCreate)
self.appendItems(params, items)
self.appendExpansion(params, expansion)
self.appendNoScale(params, noScale)
return self.execute_command(self.BF_INSERT, *params)
def bfExists(self, key, item):
"""
Checks whether an ``item`` exists in Bloom Filter ``key``.
"""
params = [key, item]
return self.execute_command(self.BF_EXISTS, *params)
def bfMExists(self, key, *items):
"""
Checks whether ``items`` exist in Bloom Filter ``key``.
"""
params = [key]
params += items
return self.execute_command(self.BF_MEXISTS, *params)
def bfScandump(self, key, iter):
"""
Begins an incremental save of the bloom filter ``key``. This is useful
for large bloom filters which cannot fit into the normal SAVE
and RESTORE model.
The first time this command is called, the value of ``iter`` should be 0.
This command will return successive (iter, data) pairs until
(0, NULL) to indicate completion.
"""
params = [key, iter]
return self.execute_command(self.BF_SCANDUMP, *params)
def bfLoadChunk(self, key, iter, data):
"""
Restores a filter previously saved using SCANDUMP. See the SCANDUMP
command for example usage.
This command will overwrite any bloom filter stored under key.
Ensure that the bloom filter will not be modified between invocations.
"""
params = [key, iter, data]
return self.execute_command(self.BF_LOADCHUNK, *params)
################## Cuckoo Filter Functions ######################
def cfCreate(self, key, capacity, expansion=None, bucket_size=None, max_iterations=None):
"""
Creates a new Cuckoo Filter ``key`` an initial ``capacity`` items.
"""
params = [key, capacity]
self.appendExpansion(params, expansion)
self.appendBucketSize(params, bucket_size)
self.appendMaxIterations(params, max_iterations)
return self.execute_command(self.CF_RESERVE, *params)
def cfAdd(self, key, item):
"""
Adds an ``item`` to a Cuckoo Filter ``key``.
"""
params = [key, item]
return self.execute_command(self.CF_ADD, *params)
def cfAddNX(self, key, item):
"""
Adds an ``item`` to a Cuckoo Filter ``key`` only if item does not yet exist.
Command might be slower that ``cfAdd``.
"""
params = [key, item]
return self.execute_command(self.CF_ADDNX, *params)
def cfInsert(self, key, items, capacity=None, nocreate=None):
"""
Adds multiple ``items`` to a Cuckoo Filter ``key``, allowing the filter to be
created with a custom ``capacity` if it does not yet exist.
``items`` must be provided as a list.
"""
params = [key]
self.appendCapacity(params, capacity)
self.appendNoCreate(params, nocreate)
self.appendItems(params, items)
return self.execute_command(self.CF_INSERT, *params)
def cfInsertNX(self, key, items, capacity=None, nocreate=None):
"""
Adds multiple ``items`` to a Cuckoo Filter ``key`` only if they do not exist yet,
allowing the filter to be created with a custom ``capacity` if it does not yet exist.
``items`` must be provided as a list.
"""
params = [key]
self.appendCapacity(params, capacity)
self.appendNoCreate(params, nocreate)
self.appendItems(params, items)
return self.execute_command(self.CF_INSERTNX, *params)
def cfExists(self, key, item):
"""
Checks whether an ``item`` exists in Cuckoo Filter ``key``.
"""
params = [key, item]
return self.execute_command(self.CF_EXISTS, *params)
def cfDel(self, key, item):
"""
Deletes ``item`` from ``key``.
"""
params = [key, item]
return self.execute_command(self.CF_DEL, *params)
def cfCount(self, key, item):
"""
Returns the number of times an ``item`` may be in the ``key``.
"""
params = [key, item]
return self.execute_command(self.CF_COUNT, *params)
def cfScandump(self, key, iter):
"""
Begins an incremental save of the Cuckoo filter ``key``. This is useful
for large Cuckoo filters which cannot fit into the normal SAVE
and RESTORE model.
The first time this command is called, the value of ``iter`` should be 0.
This command will return successive (iter, data) pairs until
(0, NULL) to indicate completion.
"""
params = [key, iter]
return self.execute_command(self.CF_SCANDUMP, *params)
def cfLoadChunk(self, key, iter, data):
"""
Restores a filter previously saved using SCANDUMP. See the SCANDUMP
command for example usage.
This command will overwrite any Cuckoo filter stored under key.
Ensure that the Cuckoo filter will not be modified between invocations.
"""
params = [key, iter, data]
return self.execute_command(self.CF_LOADDUMP, *params)
################## Count-Min Sketch Functions ######################
def cmsInitByDim(self, key, width, depth):
"""
Initializes a Count-Min Sketch ``key`` to dimensions
(``width``, ``depth``) specified by user.
"""
params = [key, width, depth]
return self.execute_command(self.CMS_INITBYDIM, *params)
def cmsInitByProb(self, key, error, probability):
"""
Initializes a Count-Min Sketch ``key`` to characteristics
(``error``, ``probability``) specified by user.
"""
params = [key, error, probability]
return self.execute_command(self.CMS_INITBYPROB, *params)
def cmsIncrBy(self, key, items, increments):
"""
Adds/increases ``items`` to a Count-Min Sketch ``key`` by ''increments''.
Both ``items`` and ``increments`` are lists.
Example - cmsIncrBy('A', ['foo'], [1])
"""
params = [key]
self.appendItemsAndIncrements(params, items, increments)
return self.execute_command(self.CMS_INCRBY, *params)
def cmsQuery(self, key, *items):
"""
Returns count for an ``item`` from ``key``.
Multiple items can be queried with one call.
"""
params = [key]
params += items
return self.execute_command(self.CMS_QUERY, *params)
def cmsMerge(self, destKey, numKeys, srcKeys, weights=[]):
"""
Merges ``numKeys`` of sketches into ``destKey``. Sketches specified in ``srcKeys``.
All sketches must have identical width and depth.
``Weights`` can be used to multiply certain sketches. Default weight is 1.
Both ``srcKeys`` and ``weights`` are lists.
"""
params = [destKey, numKeys]
params += srcKeys
self.appendWeights(params, weights)
return self.execute_command(self.CMS_MERGE, *params)
def cmsInfo(self, key):
"""
Returns width, depth and total count of the sketch.
"""
return self.execute_command(self.CMS_INFO, key)
################## Top-K Functions ######################
def topkReserve(self, key, k, width, depth, decay):
"""
Creates a new Cuckoo Filter ``key`` with desired probability of false
positives ``errorRate`` expected entries to be inserted as ``size``.
"""
params = [key, k, width, depth, decay]
return self.execute_command(self.TOPK_RESERVE, *params)
def topkAdd(self, key, *items):
"""
Adds one ``item`` or more to a Cuckoo Filter ``key``.
"""
params = [key]
params += items
return self.execute_command(self.TOPK_ADD, *params)
def topkQuery(self, key, *items):
"""
Checks whether one ``item`` or more is a Top-K item at ``key``.
"""
params = [key]
params += items
return self.execute_command(self.TOPK_QUERY, *params)
def topkCount(self, key, *items):
"""
Returns count for one ``item`` or more from ``key``.
"""
params = [key]
params += items
return self.execute_command(self.TOPK_COUNT, *params)
def topkList(self, key):
"""
Return full list of items in Top-K list of ``key```.
"""
return self.execute_command(self.TOPK_LIST, key)
def topkInfo(self, key):
"""
Returns k, width, depth and decay values of ``key``.
"""
return self.execute_command(self.TOPK_INFO, key)
def pipeline(self, transaction=True, shard_hint=None):
"""
Return a new pipeline object that can queue multiple commands for
later execution. ``transaction`` indicates whether all commands
should be executed atomically. Apart from making a group of operations
atomic, pipelines are useful for reducing the back-and-forth overhead
between the client and server.
Overridden in order to provide the right client through the pipeline.
"""
p = Pipeline(
connection_pool=self.connection_pool,
response_callbacks=self.response_callbacks,
transaction=transaction,
shard_hint=shard_hint)
return p
class Pipeline(Pipeline, Client):
"Pipeline for RedisBloom Client"