|
| 1 | +// This example demonstrates the use of the Count-Min Sketch |
| 2 | +// in the RedisBloom module (https://redisbloom.io/) |
| 3 | + |
| 4 | +import { createClient } from 'redis'; |
| 5 | + |
| 6 | +async function countMinSketch() { |
| 7 | + const client = createClient(); |
| 8 | + |
| 9 | + await client.connect(); |
| 10 | + |
| 11 | + // Delete any pre-existing Count-Min Sketch. |
| 12 | + await client.del('mycms'); |
| 13 | + |
| 14 | + // Initialize a Count-Min Sketch with error rate and probability: |
| 15 | + // https://oss.redis.com/redisbloom/CountMinSketch_Commands/#cmsinitbyprob |
| 16 | + try { |
| 17 | + await client.cms.initByProb('mycms', 0.001, 0.01); |
| 18 | + console.log('Reserved Top K.'); |
| 19 | + } catch (e) { |
| 20 | + console.log('Error, maybe RedisBloom is not installed?:'); |
| 21 | + console.log(e); |
| 22 | + } |
| 23 | + |
| 24 | + const teamMembers = [ |
| 25 | + 'leibale', |
| 26 | + 'simon', |
| 27 | + 'guy', |
| 28 | + 'suze', |
| 29 | + 'brian', |
| 30 | + 'steve', |
| 31 | + 'kyleb', |
| 32 | + 'kyleo', |
| 33 | + 'josefin', |
| 34 | + 'alex', |
| 35 | + 'nava', |
| 36 | + 'lance', |
| 37 | + 'rachel', |
| 38 | + 'kaitlyn' |
| 39 | + ]; |
| 40 | + |
| 41 | + // Store actual counts for comparison with CMS. |
| 42 | + let actualCounts = {}; |
| 43 | + |
| 44 | + // Randomly emit a team member and count them with the CMS. |
| 45 | + for (let n = 0; n < 1000; n++) { |
| 46 | + const teamMember = teamMembers[Math.floor(Math.random() * teamMembers.length)]; |
| 47 | + await client.cms.incrBy('mycms', { |
| 48 | + item: teamMember, |
| 49 | + incrementBy: 1 |
| 50 | + }); |
| 51 | + |
| 52 | + actualCounts[teamMember] = actualCounts[teamMember] ? actualCounts[teamMember] + 1 : 1; |
| 53 | + |
| 54 | + console.log(`Incremented score for ${teamMember}.`); |
| 55 | + } |
| 56 | + |
| 57 | + // Get count estimate for some team members: |
| 58 | + // https://oss.redis.com/redisbloom/CountMinSketch_Commands/#cmsquery |
| 59 | + const [ alexCount, rachelCount ] = await client.cms.query('mycms', [ |
| 60 | + 'simon', |
| 61 | + 'lance' |
| 62 | + ]); |
| 63 | + |
| 64 | + console.log(`Count estimate for alex: ${alexCount} (actual ${actualCounts.alex}).`); |
| 65 | + console.log(`Count estimate for rachel: ${rachelCount} (actual ${actualCounts.rachel}).`); |
| 66 | + |
| 67 | + // Get overall information about the Count-Min Sketch: |
| 68 | + // https://oss.redis.com/redisbloom/CountMinSketch_Commands/#cmsinfo |
| 69 | + const info = await client.cms.info('mycms'); |
| 70 | + console.log('Count-Min Sketch info:'); |
| 71 | + |
| 72 | + // info looks like this: |
| 73 | + // { |
| 74 | + // width: 2000, |
| 75 | + // depth: 7, |
| 76 | + // count: 1000 |
| 77 | + // } |
| 78 | + console.log(info); |
| 79 | + |
| 80 | + await client.quit(); |
| 81 | +} |
| 82 | + |
| 83 | +countMinSketch(); |
0 commit comments