|
| 1 | +// Example to log traffic data at intersections for the city of San Francisco. |
| 2 | +// Log license plates of each car scanned at each intersection and add to the intersections Hyperloglog. |
| 3 | +// Reference: https://www.youtube.com/watch?v=MunL8nnwscQ |
| 4 | + |
| 5 | +import { createClient } from 'redis'; |
| 6 | + |
| 7 | +const client = createClient(); |
| 8 | + |
| 9 | +await client.connect(); |
| 10 | + |
| 11 | +// Use `pfAdd` to add an element to a Hyperloglog, creating the Hyperloglog if necessary. |
| 12 | +// await client.pfAdd(key, value) |
| 13 | + |
| 14 | +// To get a count, the `pfCount` method is used. |
| 15 | +// await client.pfCount(key) |
| 16 | + |
| 17 | +try { |
| 18 | + // Corner of Market Street (ID: 12) and 10th street (ID:27). |
| 19 | + await client.pfAdd('count:sf:12:27', 'GHN34X'); |
| 20 | + await client.pfAdd('count:sf:12:27', 'ECN94Y'); |
| 21 | + await client.pfAdd('count:sf:12:27', 'VJL12V'); |
| 22 | + await client.pfAdd('count:sf:12:27', 'ORV87O'); |
| 23 | + |
| 24 | + // To get the count of Corner of Market Street (ID: 12) and 10th street (ID:27). |
| 25 | + const countForMarket10thStreet = await client.pfCount('count:sf:12:27'); |
| 26 | + console.log(`Count for Market Street & 10th Street is ${countForMarket10thStreet}`); |
| 27 | + // Count for Market Street & 10th Street is 4. |
| 28 | + |
| 29 | + // Corner of Market Street (ID: 12) and 11 street (ID:26). |
| 30 | + await client.pfAdd('count:sf:12:26', 'GHN34X'); |
| 31 | + await client.pfAdd('count:sf:12:26', 'ECN94Y'); |
| 32 | + await client.pfAdd('count:sf:12:26', 'IRV84E'); |
| 33 | + await client.pfAdd('count:sf:12:26', 'ORV87O'); |
| 34 | + await client.pfAdd('count:sf:12:26', 'TEY34S'); |
| 35 | + |
| 36 | + // To get the count of Corner of Market Street (ID: 12) and 11th street (ID:26). |
| 37 | + const countForMarket11thStreet = await client.pfCount('count:sf:12:26'); |
| 38 | + console.log(`Count for Market Street & 11th Street is ${countForMarket11thStreet}`); |
| 39 | + // Count for Market Street & 11th Street is 5. |
| 40 | + |
| 41 | + // To merge the Hyperloglogs `count:sf:12:26` and `count:sf:12:27`. |
| 42 | + await client.pfMerge('count:merge', ['count:sf:12:27', 'count:sf:12:26']); |
| 43 | + const countMerge = await client.pfCount('count:merge'); |
| 44 | + console.log(`Count for the merge is ${countMerge}`); |
| 45 | + // Count for the merge is 6. |
| 46 | +} catch (e) { |
| 47 | + // something went wrong. |
| 48 | + console.error(e); |
| 49 | +} |
| 50 | + |
| 51 | +await client.quit(); |
0 commit comments