-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathcount-min-sketch.js
80 lines (65 loc) · 1.93 KB
/
count-min-sketch.js
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
// This example demonstrates the use of the Count-Min Sketch
// in the RedisBloom module (https://redis.io/docs/stack/bloom/)
import { createClient } from 'redis';
const client = createClient();
await client.connect();
// Delete any pre-existing Count-Min Sketch.
await client.del('mycms');
// Initialize a Count-Min Sketch with error rate and probability:
// https://redis.io/commands/cms.initbyprob/
try {
await client.cms.initByProb('mycms', 0.001, 0.01);
console.log('Reserved Count Min Sketch.');
} catch (e) {
console.log('Error, maybe RedisBloom is not installed?:');
console.log(e);
}
const teamMembers = [
'leibale',
'simon',
'guy',
'suze',
'brian',
'steve',
'kyleb',
'kyleo',
'josefin',
'alex',
'nava',
'lance',
'rachel',
'kaitlyn'
];
// Store actual counts for comparison with CMS.
let actualCounts = {};
// Randomly emit a team member and count them with the CMS.
// https://redis.io/commands/cms.incrby/
for (let n = 0; n < 1000; n++) {
const teamMember = teamMembers[Math.floor(Math.random() * teamMembers.length)];
await client.cms.incrBy('mycms', {
item: teamMember,
incrementBy: 1
});
actualCounts[teamMember] = actualCounts[teamMember] ? actualCounts[teamMember] + 1 : 1;
console.log(`Incremented score for ${teamMember}.`);
}
// Get count estimate for some team members:
// https://redis.io/commands/cms.query/
const [ alexCount, rachelCount ] = await client.cms.query('mycms', [
'alex',
'rachel'
]);
console.log(`Count estimate for alex: ${alexCount} (actual ${actualCounts.alex}).`);
console.log(`Count estimate for rachel: ${rachelCount} (actual ${actualCounts.rachel}).`);
// Get overall information about the Count-Min Sketch:
// https://redis.io/commands/cms.info/
const info = await client.cms.info('mycms');
console.log('Count-Min Sketch info:');
// info looks like this:
// {
// width: 2000,
// depth: 7,
// count: 1000
// }
console.log(info);
await client.quit();