forked from redis/node-redis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtopk.js
94 lines (80 loc) · 2.43 KB
/
topk.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// This example demonstrates the use of the Top K
// in the RedisBloom module (https://redisbloom.io/)
import { createClient } from 'redis';
async function topK() {
const client = createClient();
await client.connect();
// Delete any pre-existing Top K.
await client.del('mytopk');
// Reserve a Top K to track the 10 most common items.
// https://oss.redis.com/redisbloom/TopK_Commands/#topkreserve
try {
await client.topK.reserve('mytopk', 10);
console.log('Reserved Top K.');
} catch (e) {
if (e.message.endsWith('key already exists')) {
console.log('Top K already reserved.');
} else {
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'
];
// Add random counts for random team members with TOPK.INCRBY
for (let n = 0; n < 1000; n++) {
const teamMember = teamMembers[Math.floor(Math.random() * teamMembers.length)];
const points = Math.floor(Math.random() * 1000) + 1;
await client.topK.incrBy('mytopk', {
item: teamMember,
incrementBy: points
});
console.log(`Added ${points} points for ${teamMember}.`);
}
// List out the top 10 with TOPK.LIST
const top10 = await client.topK.list('mytopk');
console.log('The top 10:');
// top10 looks like this:
// [
// 'guy', 'nava',
// 'kaitlyn', 'brian',
// 'simon', 'suze',
// 'lance', 'alex',
// 'steve', 'kyleo'
// ]
console.log(top10);
// Check if a few team members are in the top 10 with TOPK.QUERY:
const [ steve, suze, leibale, frederick ] = await client.topK.query('mytopk', [
'steve',
'suze',
'leibale',
'frederick'
]);
console.log(`steve ${steve === 1 ? 'is': 'is not'} in the top 10.`);
console.log(`suze ${suze === 1 ? 'is': 'is not'} in the top 10.`);
console.log(`leibale ${leibale === 1 ? 'is': 'is not'} in the top 10.`);
console.log(`frederick ${frederick === 1 ? 'is': 'is not'} in the top 10.`);
// Get count estimate for some team members:
const [ simonCount, lanceCount ] = await client.topK.count('mytopk', [
'simon',
'lance'
]);
console.log(`Count estimate for simon: ${simonCount}.`);
console.log(`Count estimate for lance: ${lanceCount}.`);
await client.quit();
}
topK();