1
0
mirror of https://github.com/redis/node-redis.git synced 2025-08-06 02:15:48 +03:00

Updates examples. (#2219)

* Updates examples.

* Added command link for hset.
This commit is contained in:
Simon Prickett
2022-08-15 13:39:28 +01:00
committed by GitHub
parent 60ad6aab0b
commit f3462abf33
19 changed files with 972 additions and 1019 deletions

View File

@@ -53,7 +53,7 @@ When adding a new example, please follow these guidelines:
* Use semicolons * Use semicolons
* Use `async` and `await` * Use `async` and `await`
* Use single quotes, `'hello'` not `"hello"` * Use single quotes, `'hello'` not `"hello"`
* Place your example code in a single `async` function where possible, named according to the file name e.g. `add-to-stream.js` would contain `const addtoStream = async () => { ... };`, and call this function at the end of the file e.g. `addToStream();` * Use [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) when embedding expressions in strings
* Unless your example requires a connection string, assume Redis is on the default localhost port 6379 with no password * Unless your example requires a connection string, assume Redis is on the default localhost port 6379 with no password
* Use meaningful example data, let's not use `foo`, `bar`, `baz` etc! * Use meaningful example data, let's not use `foo`, `bar`, `baz` etc!
* Leave an empty line at the end of your `.js` file * Leave an empty line at the end of your `.js` file
@@ -71,10 +71,11 @@ Here's a starter template for adding a new example, imagine this is stored in `d
// Set up the data in redis-cli using these commands: // Set up the data in redis-cli using these commands:
// <add your command(s) here, one per line> // <add your command(s) here, one per line>
//
// Alternatively, add code that sets up the data.
import { createClient } from 'redis'; import { createClient } from 'redis';
async function doSomething() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
@@ -82,7 +83,5 @@ async function doSomething() {
// Add your example code here... // Add your example code here...
await client.quit(); await client.quit();
}
doSomething();
``` ```

View File

@@ -6,7 +6,6 @@
import { createClient, commandOptions } from 'redis'; import { createClient, commandOptions } from 'redis';
async function blockingListPop() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
@@ -21,12 +20,11 @@ async function blockingListPop() {
await client.lPush(keyName, 'value'); await client.lPush(keyName, 'value');
await blpopPromise; const listItem = await blpopPromise;
console.log('blpopPromise resolved'); console.log('blpopPromise resolved');
console.log(keyName); // listItem will be:
// {"key":"keyName","element":"value"}
console.log(`listItem is '${JSON.stringify(listItem)}'`);
await client.quit(); await client.quit();
}
blockingListPop();

View File

@@ -1,9 +1,8 @@
// This example demonstrates the use of the Bloom Filter // This example demonstrates the use of the Bloom Filter
// in the RedisBloom module (https://redisbloom.io/) // in the RedisBloom module (https://redis.io/docs/stack/bloom/)
import { createClient } from 'redis'; import { createClient } from 'redis';
async function bloomFilter() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
@@ -12,7 +11,7 @@ async function bloomFilter() {
await client.del('mybloom'); await client.del('mybloom');
// Reserve a Bloom Filter with configurable error rate and capacity. // Reserve a Bloom Filter with configurable error rate and capacity.
// https://oss.redis.com/redisbloom/Bloom_Commands/#bfreserve // https://redis.io/commands/bf.reserve/
try { try {
await client.bf.reserve('mybloom', 0.01, 1000); await client.bf.reserve('mybloom', 0.01, 1000);
console.log('Reserved Bloom Filter.'); console.log('Reserved Bloom Filter.');
@@ -26,6 +25,7 @@ async function bloomFilter() {
} }
// Add items to Bloom Filter individually with BF.ADD command. // Add items to Bloom Filter individually with BF.ADD command.
// https://redis.io/commands/bf.add/
await Promise.all([ await Promise.all([
client.bf.add('mybloom', 'leibale'), client.bf.add('mybloom', 'leibale'),
client.bf.add('mybloom', 'simon'), client.bf.add('mybloom', 'simon'),
@@ -40,6 +40,7 @@ async function bloomFilter() {
]); ]);
// Add multiple items to Bloom Filter at once with BF.MADD command. // Add multiple items to Bloom Filter at once with BF.MADD command.
// https://redis.io/commands/bf.madd/
await client.bf.mAdd('mybloom', [ await client.bf.mAdd('mybloom', [
'kaitlyn', 'kaitlyn',
'rachel' 'rachel'
@@ -48,10 +49,12 @@ async function bloomFilter() {
console.log('Added members to Bloom Filter.'); console.log('Added members to Bloom Filter.');
// Check whether a member exists with the BF.EXISTS command. // Check whether a member exists with the BF.EXISTS command.
// https://redis.io/commands/bf.exists/
const simonExists = await client.bf.exists('mybloom', 'simon'); const simonExists = await client.bf.exists('mybloom', 'simon');
console.log(`simon ${simonExists ? 'may' : 'does not'} exist in the Bloom Filter.`); console.log(`simon ${simonExists ? 'may' : 'does not'} exist in the Bloom Filter.`);
// Check whether multiple members exist with the BF.MEXISTS command: // Check whether multiple members exist with the BF.MEXISTS command.
// https://redis.io/commands/bf.mexists/
const [ lanceExists, leibaleExists ] = await client.bf.mExists('mybloom', [ const [ lanceExists, leibaleExists ] = await client.bf.mExists('mybloom', [
'lance', 'lance',
'leibale' 'leibale'
@@ -60,7 +63,8 @@ async function bloomFilter() {
console.log(`lance ${lanceExists ? 'may' : 'does not'} exist in the Bloom Filter.`); console.log(`lance ${lanceExists ? 'may' : 'does not'} exist in the Bloom Filter.`);
console.log(`leibale ${leibaleExists ? 'may' : 'does not'} exist in the Bloom Filter.`); console.log(`leibale ${leibaleExists ? 'may' : 'does not'} exist in the Bloom Filter.`);
// Get stats for the Bloom Filter with the BF.INFO command: // Get stats for the Bloom Filter with the BF.INFO command.
// https://redis.io/commands/bf.info/
const info = await client.bf.info('mybloom'); const info = await client.bf.info('mybloom');
// info looks like this: // info looks like this:
// //
@@ -74,6 +78,3 @@ async function bloomFilter() {
console.log(info); console.log(info);
await client.quit(); await client.quit();
}
bloomFilter();

View File

@@ -3,7 +3,6 @@
import { createClient } from 'redis'; import { createClient } from 'redis';
async function commandWithModifiers() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
@@ -14,7 +13,7 @@ async function commandWithModifiers() {
GET: true GET: true
}); });
console.log(result); //nil console.log(result); //null
result = await client.set('mykey', 'newvalue', { result = await client.set('mykey', 'newvalue', {
EX: 60, EX: 60,
@@ -24,7 +23,3 @@ async function commandWithModifiers() {
console.log(result); //myvalue console.log(result); //myvalue
await client.quit(); await client.quit();
}
commandWithModifiers();

View File

@@ -7,7 +7,6 @@
import { createClient } from 'redis'; import { createClient } from 'redis';
async function connectWithACLUser() {
const client = createClient({ const client = createClient({
url: 'redis://testuser:testpassword@127.0.0.1:6379' url: 'redis://testuser:testpassword@127.0.0.1:6379'
}); });
@@ -25,6 +24,3 @@ async function connectWithACLUser() {
} }
await client.quit(); await client.quit();
}
connectWithACLUser();

View File

@@ -1,9 +1,8 @@
// This example demonstrates the use of the Count-Min Sketch // This example demonstrates the use of the Count-Min Sketch
// in the RedisBloom module (https://redisbloom.io/) // in the RedisBloom module (https://redis.io/docs/stack/bloom/)
import { createClient } from 'redis'; import { createClient } from 'redis';
async function countMinSketch() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
@@ -12,10 +11,10 @@ async function countMinSketch() {
await client.del('mycms'); await client.del('mycms');
// Initialize a Count-Min Sketch with error rate and probability: // Initialize a Count-Min Sketch with error rate and probability:
// https://oss.redis.com/redisbloom/CountMinSketch_Commands/#cmsinitbyprob // https://redis.io/commands/cms.initbyprob/
try { try {
await client.cms.initByProb('mycms', 0.001, 0.01); await client.cms.initByProb('mycms', 0.001, 0.01);
console.log('Initialized Count-Min Sketch.'); console.log('Reserved Count Min Sketch.');
} catch (e) { } catch (e) {
console.log('Error, maybe RedisBloom is not installed?:'); console.log('Error, maybe RedisBloom is not installed?:');
console.log(e); console.log(e);
@@ -42,6 +41,7 @@ async function countMinSketch() {
let actualCounts = {}; let actualCounts = {};
// Randomly emit a team member and count them with the CMS. // Randomly emit a team member and count them with the CMS.
// https://redis.io/commands/cms.incrby/
for (let n = 0; n < 1000; n++) { for (let n = 0; n < 1000; n++) {
const teamMember = teamMembers[Math.floor(Math.random() * teamMembers.length)]; const teamMember = teamMembers[Math.floor(Math.random() * teamMembers.length)];
await client.cms.incrBy('mycms', { await client.cms.incrBy('mycms', {
@@ -55,17 +55,17 @@ async function countMinSketch() {
} }
// Get count estimate for some team members: // Get count estimate for some team members:
// https://oss.redis.com/redisbloom/CountMinSketch_Commands/#cmsquery // https://redis.io/commands/cms.query/
const [ alexCount, rachelCount ] = await client.cms.query('mycms', [ const [ alexCount, rachelCount ] = await client.cms.query('mycms', [
'simon', 'alex',
'lance' 'rachel'
]); ]);
console.log(`Count estimate for alex: ${alexCount} (actual ${actualCounts.alex}).`); console.log(`Count estimate for alex: ${alexCount} (actual ${actualCounts.alex}).`);
console.log(`Count estimate for rachel: ${rachelCount} (actual ${actualCounts.rachel}).`); console.log(`Count estimate for rachel: ${rachelCount} (actual ${actualCounts.rachel}).`);
// Get overall information about the Count-Min Sketch: // Get overall information about the Count-Min Sketch:
// https://oss.redis.com/redisbloom/CountMinSketch_Commands/#cmsinfo // https://redis.io/commands/cms.info/
const info = await client.cms.info('mycms'); const info = await client.cms.info('mycms');
console.log('Count-Min Sketch info:'); console.log('Count-Min Sketch info:');
@@ -78,6 +78,3 @@ async function countMinSketch() {
console.log(info); console.log(info);
await client.quit(); await client.quit();
}
countMinSketch();

View File

@@ -1,9 +1,8 @@
// This example demonstrates the use of the Cuckoo Filter // This example demonstrates the use of the Cuckoo Filter
// in the RedisBloom module (https://redisbloom.io/) // in the RedisBloom module (https://redis.io/docs/stack/bloom/)
import { createClient } from 'redis'; import { createClient } from 'redis';
async function cuckooFilter() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
@@ -12,7 +11,7 @@ async function cuckooFilter() {
await client.del('mycuckoo'); await client.del('mycuckoo');
// Reserve a Cuckoo Filter with a capacity of 10000 items. // Reserve a Cuckoo Filter with a capacity of 10000 items.
// https://oss.redis.com/redisbloom/Cuckoo_Commands/#cfreserve // https://redis.io/commands/cf.reserve/
try { try {
await client.cf.reserve('mycuckoo', 10000); await client.cf.reserve('mycuckoo', 10000);
console.log('Reserved Cuckoo Filter.'); console.log('Reserved Cuckoo Filter.');
@@ -22,7 +21,7 @@ async function cuckooFilter() {
} }
// Add items to Cuckoo Filter individually with CF.ADD command. // Add items to Cuckoo Filter individually with CF.ADD command.
https://oss.redis.com/redisbloom/Cuckoo_Commands/#cfadd // https://redis.io/commands/cf.add/
await Promise.all([ await Promise.all([
client.cf.add('mycuckoo', 'leibale'), client.cf.add('mycuckoo', 'leibale'),
client.cf.add('mycuckoo', 'simon'), client.cf.add('mycuckoo', 'simon'),
@@ -37,7 +36,7 @@ async function cuckooFilter() {
]); ]);
// Add items to the Cuckoo Filter only if they don't exist in it... // Add items to the Cuckoo Filter only if they don't exist in it...
// https://oss.redis.com/redisbloom/Cuckoo_Commands/#cfaddnx // https://redis.io/commands/cf.addnx/
const nxReply = await Promise.all([ const nxReply = await Promise.all([
client.cf.addNX('mycuckoo', 'kaitlyn'), // New client.cf.addNX('mycuckoo', 'kaitlyn'), // New
client.cf.addNX('mycuckoo', 'rachel'), // New client.cf.addNX('mycuckoo', 'rachel'), // New
@@ -56,10 +55,12 @@ async function cuckooFilter() {
console.log(nxReply); console.log(nxReply);
// Check whether a member exists with the CF.EXISTS command. // Check whether a member exists with the CF.EXISTS command.
// https://redis.io/commands/cf.exists/
const simonExists = await client.bf.exists('mycuckoo', 'simon'); const simonExists = await client.bf.exists('mycuckoo', 'simon');
console.log(`simon ${simonExists ? 'may' : 'does not'} exist in the Cuckoo Filter.`); console.log(`simon ${simonExists ? 'may' : 'does not'} exist in the Cuckoo Filter.`);
// Get stats for the Cuckoo Filter with the CF.INFO command: // Get stats for the Cuckoo Filter with the CF.INFO command:
// https://redis.io/commands/cf.info/
const info = await client.cf.info('mycuckoo'); const info = await client.cf.info('mycuckoo');
// info looks like this: // info looks like this:
@@ -76,6 +77,3 @@ async function cuckooFilter() {
console.log(info); console.log(info);
await client.quit(); await client.quit();
}
cuckooFilter();

View File

@@ -2,7 +2,6 @@
import { createClient } from 'redis'; import { createClient } from 'redis';
async function getServerTime() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
@@ -11,6 +10,3 @@ async function getServerTime() {
console.log(serverTime); console.log(serverTime);
await client.quit(); await client.quit();
}
getServerTime();

View File

@@ -3,7 +3,6 @@
import { createClient, defineScript } from 'redis'; import { createClient, defineScript } from 'redis';
async function luaMultiIncr() {
const client = createClient({ const client = createClient({
scripts: { scripts: {
mincr: defineScript({ mincr: defineScript({
@@ -26,6 +25,3 @@ async function luaMultiIncr() {
console.log(await client.mincr('mykey', 'myotherkey', 10)); // [ 15, 10 ] console.log(await client.mincr('mykey', 'myotherkey', 10)); // [ 15, 10 ]
await client.quit(); await client.quit();
}
luaMultiIncr();

View File

@@ -2,7 +2,6 @@
import { createClient } from 'redis'; import { createClient } from 'redis';
async function managingJSON() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
@@ -43,25 +42,25 @@ async function managingJSON() {
// Retrieve the name and age of the second pet in the pets array. // Retrieve the name and age of the second pet in the pets array.
let results = await client.json.get('noderedis:jsondata', { let results = await client.json.get('noderedis:jsondata', {
path: [ path: [
'.pets[1].name', '$.pets[1].name',
'.pets[1].age' '$.pets[1].age'
] ]
}); });
// { '.pets[1].name': 'Rex', '.pets[1].age': 3 } // { '$.pets[1].name': [ 'Rex' ], '$.pets[1].age': [ 3 ] }
console.log(results); console.log(results);
// Goldie had a birthday, increment the age... // Goldie had a birthday, increment the age...
await client.json.numIncrBy('noderedis:jsondata', '.pets[2].age', 1); await client.json.numIncrBy('noderedis:jsondata', '$.pets[2].age', 1);
results = await client.json.get('noderedis:jsondata', { results = await client.json.get('noderedis:jsondata', {
path: '.pets[2].age' path: '$.pets[2].age'
}); });
// Goldie is 3 years old now. // Goldie is 3 years old now.
console.log(`Goldie is ${JSON.stringify(results)} years old now.`); console.log(`Goldie is ${JSON.stringify(results[0])} years old now.`);
// Add a new pet... // Add a new pet...
await client.json.arrAppend('noderedis:jsondata', '.pets', { await client.json.arrAppend('noderedis:jsondata', '$.pets', {
name: 'Robin', name: 'Robin',
species: 'bird', species: 'bird',
isMammal: false, isMammal: false,
@@ -69,13 +68,9 @@ async function managingJSON() {
}); });
// How many pets do we have now? // How many pets do we have now?
const numPets = await client.json.arrLen('noderedis:jsondata', '.pets'); const numPets = await client.json.arrLen('noderedis:jsondata', '$.pets');
// We now have 4 pets. // We now have 4 pets.
console.log(`We now have ${numPets} pets.`); console.log(`We now have ${numPets} pets.`);
await client.quit(); await client.quit();
}
managingJSON();

View File

@@ -3,14 +3,13 @@
import { createClient, SchemaFieldTypes } from 'redis'; import { createClient, SchemaFieldTypes } from 'redis';
async function searchHashes() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
// Create an index... // Create an index...
try { try {
// Documentation: https://oss.redis.com/redisearch/Commands/#ftcreate // Documentation: https://redis.io/commands/ft.create/
await client.ft.create('idx:animals', { await client.ft.create('idx:animals', {
name: { name: {
type: SchemaFieldTypes.TEXT, type: SchemaFieldTypes.TEXT,
@@ -33,6 +32,7 @@ async function searchHashes() {
} }
// Add some sample data... // Add some sample data...
// https://redis.io/commands/hset/
await Promise.all([ await Promise.all([
client.hSet('noderedis:animals:1', {name: 'Fluffy', species: 'cat', age: 3}), client.hSet('noderedis:animals:1', {name: 'Fluffy', species: 'cat', age: 3}),
client.hSet('noderedis:animals:2', {name: 'Ginger', species: 'cat', age: 4}), client.hSet('noderedis:animals:2', {name: 'Ginger', species: 'cat', age: 4}),
@@ -41,15 +41,15 @@ async function searchHashes() {
]); ]);
// Perform a search query, find all the dogs... sort by age, descending. // Perform a search query, find all the dogs... sort by age, descending.
// Documentation: https://oss.redis.com/redisearch/Commands/#ftsearch // Documentation: https://redis.io/commands/ft.search/
// Query syntax: https://oss.redis.com/redisearch/Query_Syntax/ // Query syntax: https://redis.io/docs/stack/search/reference/query_syntax/
const results = await client.ft.search( const results = await client.ft.search(
'idx:animals', 'idx:animals',
'@species:{dog}', '@species:{dog}',
{ {
SORTBY: { SORTBY: {
BY: 'age', BY: 'age',
DIRECTION: 'DESC' // or 'ASC' (default if DIRECTION is not present) DIRECTION: 'DESC' // or 'ASC (default if DIRECTION is not present)
} }
} }
); );
@@ -61,17 +61,17 @@ async function searchHashes() {
// { // {
// id: 'noderedis:animals:3', // id: 'noderedis:animals:3',
// value: { // value: {
// age: '9',
// name: 'Rover', // name: 'Rover',
// species: 'dog' // species: 'dog',
// age: '9'
// } // }
// }, // },
// { // {
// id: 'noderedis:animals:4', // id: 'noderedis:animals:4',
// value: { // value: {
// age: '7',
// name: 'Fido', // name: 'Fido',
// species: 'dog' // species: 'dog',
// age: '7'
// } // }
// } // }
// ] // ]
@@ -86,6 +86,3 @@ async function searchHashes() {
} }
await client.quit(); await client.quit();
}
searchHashes();

View File

@@ -1,13 +1,16 @@
// This example demonstrates how to use RediSearch and RedisJSON together. // This example demonstrates how to use RediSearch and RedisJSON together.
// Requires both the RediSearch and RedisJSON modules:
// https://redis.io/docs/stack/search/
// https://redis.io/docs/stack/json/
import { createClient, SchemaFieldTypes, AggregateGroupByReducers, AggregateSteps } from 'redis'; import { createClient, SchemaFieldTypes, AggregateGroupByReducers, AggregateSteps } from 'redis';
async function searchJSON() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
// Create an index. // Create an index.
// https://redis.io/commands/ft.create/
try { try {
await client.ft.create('idx:users', { await client.ft.create('idx:users', {
'$.name': { '$.name': {
@@ -41,6 +44,7 @@ async function searchJSON() {
} }
// Add some users. // Add some users.
// https://redis.io/commands/json.set/
await Promise.all([ await Promise.all([
client.json.set('noderedis:users:1', '$', { client.json.set('noderedis:users:1', '$', {
name: 'Alice', name: 'Alice',
@@ -59,7 +63,7 @@ async function searchJSON() {
// Search all users under 30 // Search all users under 30
console.log('Users under 30 years old:'); console.log('Users under 30 years old:');
console.log( console.log(
// https://oss.redis.com/redisearch/Commands/#ftsearch // https://redis.io/commands/ft.search/
JSON.stringify( JSON.stringify(
await client.ft.search('idx:users', '@age:[0 30]'), await client.ft.search('idx:users', '@age:[0 30]'),
null, null,
@@ -83,7 +87,7 @@ async function searchJSON() {
// Find a user by email - note we need to escape . and @ characters // Find a user by email - note we need to escape . and @ characters
// in the email address. This applies for other punctuation too. // in the email address. This applies for other punctuation too.
// https://oss.redis.com/redisearch/Tags/#including_punctuation_in_tags // https://redis.io/docs/stack/search/reference/tags/#including-punctuation-in-tags
console.log('Users with email "bob@somewhere.gov":'); console.log('Users with email "bob@somewhere.gov":');
const emailAddress = 'bob@somewhere.gov'.replace(/[.@]/g, '\\$&'); const emailAddress = 'bob@somewhere.gov'.replace(/[.@]/g, '\\$&');
console.log( console.log(
@@ -109,7 +113,7 @@ async function searchJSON() {
// } // }
// Some aggregrations, what's the average age and total number of coins... // Some aggregrations, what's the average age and total number of coins...
// https://oss.redis.com/redisearch/Commands/#ftaggregate // https://redis.io/commands/ft.aggregate/
console.log('Aggregation Demo:'); console.log('Aggregation Demo:');
console.log( console.log(
JSON.stringify( JSON.stringify(
@@ -142,6 +146,3 @@ async function searchJSON() {
// } // }
await client.quit(); await client.quit();
}
searchJSON();

View File

@@ -4,7 +4,6 @@
import { createClient } from 'redis'; import { createClient } from 'redis';
async function setScan() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
@@ -14,6 +13,3 @@ async function setScan() {
} }
await client.quit(); await client.quit();
}
setScan();

View File

@@ -3,7 +3,6 @@
import { createClient } from 'redis'; import { createClient } from 'redis';
async function addToSortedSet() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
@@ -30,6 +29,3 @@ async function addToSortedSet() {
} }
await client.quit(); await client.quit();
}
addToSortedSet();

View File

@@ -1,4 +1,6 @@
// A sample stream consumer using the blocking variant of XREADGROUP. // A sample stream consumer using the blocking variant of XREADGROUP.
// https://redis.io/commands/xreadgroup/
// This consumer works in collaboration with other instances of itself // This consumer works in collaboration with other instances of itself
// in the same consumer group such that the group as a whole receives // in the same consumer group such that the group as a whole receives
// every entry from the stream. // every entry from the stream.
@@ -20,7 +22,6 @@
import { createClient, commandOptions } from 'redis'; import { createClient, commandOptions } from 'redis';
async function streamConsumerGroup() {
const client = createClient(); const client = createClient();
if (process.argv.length !== 3) { if (process.argv.length !== 3) {
@@ -34,6 +35,7 @@ async function streamConsumerGroup() {
// Create the consumer group (and stream) if needed... // Create the consumer group (and stream) if needed...
try { try {
// https://redis.io/commands/xgroup-create/
await client.xGroupCreate('mystream', 'myconsumergroup', '0', { await client.xGroupCreate('mystream', 'myconsumergroup', '0', {
MKSTREAM: true MKSTREAM: true
}); });
@@ -46,6 +48,7 @@ async function streamConsumerGroup() {
while (true) { while (true) {
try { try {
// https://redis.io/commands/xreadgroup/
let response = await client.xReadGroup( let response = await client.xReadGroup(
commandOptions({ commandOptions({
isolated: true isolated: true
@@ -86,6 +89,7 @@ async function streamConsumerGroup() {
// Use XACK to acknowledge successful processing of this // Use XACK to acknowledge successful processing of this
// stream entry. // stream entry.
// https://redis.io/commands/xack/
const entryId = response[0].messages[0].id; const entryId = response[0].messages[0].id;
await client.xAck('mystream', 'myconsumergroup', entryId); await client.xAck('mystream', 'myconsumergroup', entryId);
@@ -99,6 +103,3 @@ async function streamConsumerGroup() {
console.error(err); console.error(err);
} }
} }
}
streamConsumerGroup();

View File

@@ -1,9 +1,9 @@
// A sample stream consumer using the blocking variant of XREAD. // A sample stream consumer using the blocking variant of XREAD.
// https://redis.io/commands/xread/
// This consumes entries from a stream created by stream-producer.js // This consumes entries from a stream created by stream-producer.js
import { createClient, commandOptions } from 'redis'; import { createClient, commandOptions } from 'redis';
async function streamConsumer() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
@@ -59,6 +59,3 @@ async function streamConsumer() {
console.error(err); console.error(err);
} }
} }
}
streamConsumer();

View File

@@ -1,7 +1,7 @@
// A sample stream producer using XADD. // A sample stream producer using XADD.
// https://redis.io/commands/xadd/
import { createClient } from 'redis'; import { createClient } from 'redis';
async function streamProducer() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
@@ -23,7 +23,7 @@ async function streamProducer() {
await client.xAdd( await client.xAdd(
'mytrimmedstream', 'mytrimmedstream',
id, // Re-use the ID from the previous stream. '*',
// Payload to add to the stream: // Payload to add to the stream:
{ {
i: i.toString() i: i.toString()
@@ -41,13 +41,10 @@ async function streamProducer() {
} }
// Take a look at how many entries are in the streams... // Take a look at how many entries are in the streams...
// https://redis.io/commands/xlen/
// Should be 10000: // Should be 10000:
console.log(`Length of mystream: ${await client.xLen('mystream')}.`); console.log(`Length of mystream: ${await client.xLen('mystream')}.`);
// Should be approximately 1000: // Should be approximately 1000:
console.log(`Length of mytrimmedstream: ${await client.xLen('mytrimmedstream')}.`); console.log(`Length of mytrimmedstream: ${await client.xLen('mytrimmedstream')}.`);
await client.quit(); await client.quit();
}
streamProducer();

View File

@@ -1,10 +1,9 @@
// Add data to a Redis TimeSeries and query it. // Add data to a Redis TimeSeries and query it.
// Requires the RedisTimeSeries module: https://redistimeseries.io/ // Requires the RedisTimeSeries module: https://redis.io/docs/stack/timeseries/
import { createClient } from 'redis'; import { createClient } from 'redis';
import { TimeSeriesDuplicatePolicies, TimeSeriesEncoding, TimeSeriesAggregationType } from '@redis/time-series'; import { TimeSeriesDuplicatePolicies, TimeSeriesEncoding, TimeSeriesAggregationType } from '@redis/time-series';
async function timeSeries() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
@@ -12,7 +11,7 @@ async function timeSeries() {
try { try {
// Create a timeseries // Create a timeseries
// https://oss.redis.com/redistimeseries/commands/#tscreate // https://redis.io/commands/ts.create/
const created = await client.ts.create('mytimeseries', { const created = await client.ts.create('mytimeseries', {
RETENTION: 86400000, // 1 day in milliseconds RETENTION: 86400000, // 1 day in milliseconds
ENCODING: TimeSeriesEncoding.UNCOMPRESSED, // No compression ENCODING: TimeSeriesEncoding.UNCOMPRESSED, // No compression
@@ -32,7 +31,7 @@ async function timeSeries() {
while (num < 10000) { while (num < 10000) {
// Add a new value to the timeseries, providing our own timestamp: // Add a new value to the timeseries, providing our own timestamp:
// https://oss.redis.com/redistimeseries/commands/#tsadd // https://redis.io/commands/ts.add/
await client.ts.add('mytimeseries', currentTimestamp, value); await client.ts.add('mytimeseries', currentTimestamp, value);
console.log(`Added timestamp ${currentTimestamp}, value ${value}.`); console.log(`Added timestamp ${currentTimestamp}, value ${value}.`);
@@ -42,7 +41,7 @@ async function timeSeries() {
} }
// Add multiple values to the timeseries in round trip to the server: // Add multiple values to the timeseries in round trip to the server:
// https://oss.redis.com/redistimeseries/commands/#tsmadd // https://redis.io/commands/ts.madd/
const response = await client.ts.mAdd([{ const response = await client.ts.mAdd([{
key: 'mytimeseries', key: 'mytimeseries',
timestamp: currentTimestamp + 60000, timestamp: currentTimestamp + 60000,
@@ -59,7 +58,7 @@ async function timeSeries() {
} }
// Update timeseries retention with TS.ALTER: // Update timeseries retention with TS.ALTER:
// https://oss.redis.com/redistimeseries/commands/#tsalter // https://redis.io/commands/ts.alter/
const alterResponse = await client.ts.alter('mytimeseries', { const alterResponse = await client.ts.alter('mytimeseries', {
RETENTION: 0 // Keep the entries forever RETENTION: 0 // Keep the entries forever
}); });
@@ -69,7 +68,7 @@ async function timeSeries() {
} }
// Query the timeseries with TS.RANGE: // Query the timeseries with TS.RANGE:
// https://oss.redis.com/redistimeseries/commands/#tsrangetsrevrange // https://redis.io/commands/ts.range/
const fromTimestamp = 1640995200000; // Jan 1 2022 00:00:00 const fromTimestamp = 1640995200000; // Jan 1 2022 00:00:00
const toTimestamp = 1640995260000; // Jan 1 2022 00:01:00 const toTimestamp = 1640995260000; // Jan 1 2022 00:01:00
const rangeResponse = await client.ts.range('mytimeseries', fromTimestamp, toTimestamp, { const rangeResponse = await client.ts.range('mytimeseries', fromTimestamp, toTimestamp, {
@@ -95,7 +94,7 @@ async function timeSeries() {
console.log(rangeResponse); console.log(rangeResponse);
// Get some information about the state of the timeseries. // Get some information about the state of the timeseries.
// https://oss.redis.com/redistimeseries/commands/#tsinfo // https://redis.io/commands/ts.info/
const tsInfo = await client.ts.info('mytimeseries'); const tsInfo = await client.ts.info('mytimeseries');
// tsInfo looks like this: // tsInfo looks like this:
@@ -121,6 +120,3 @@ async function timeSeries() {
} }
await client.quit(); await client.quit();
}
timeSeries();

View File

@@ -1,9 +1,8 @@
// This example demonstrates the use of the Top K // This example demonstrates the use of the Top K
// in the RedisBloom module (https://redisbloom.io/) // in the RedisBloom module (https://redis.io/docs/stack/bloom/)
import { createClient } from 'redis'; import { createClient } from 'redis';
async function topK() {
const client = createClient(); const client = createClient();
await client.connect(); await client.connect();
@@ -12,9 +11,9 @@ async function topK() {
await client.del('mytopk'); await client.del('mytopk');
// Reserve a Top K to track the 10 most common items. // Reserve a Top K to track the 10 most common items.
// https://oss.redis.com/redisbloom/TopK_Commands/#topkreserve // https://redis.io/commands/topk.reserve/
try { try {
await client.topK.reserve('mytopk', 10); await client.topK.reserve('mytopk', 10, { width: 400, depth: 10, decay: 0.9 });
console.log('Reserved Top K.'); console.log('Reserved Top K.');
} catch (e) { } catch (e) {
if (e.message.endsWith('key already exists')) { if (e.message.endsWith('key already exists')) {
@@ -43,6 +42,7 @@ async function topK() {
]; ];
// Add random counts for random team members with TOPK.INCRBY // Add random counts for random team members with TOPK.INCRBY
// https://redis.io/commands/topk.incrby/
for (let n = 0; n < 1000; n++) { for (let n = 0; n < 1000; n++) {
const teamMember = teamMembers[Math.floor(Math.random() * teamMembers.length)]; const teamMember = teamMembers[Math.floor(Math.random() * teamMembers.length)];
const points = Math.floor(Math.random() * 1000) + 1; const points = Math.floor(Math.random() * 1000) + 1;
@@ -54,6 +54,7 @@ async function topK() {
} }
// List out the top 10 with TOPK.LIST // List out the top 10 with TOPK.LIST
// https://redis.io/commands/topk.list/
const top10 = await client.topK.list('mytopk'); const top10 = await client.topK.list('mytopk');
console.log('The top 10:'); console.log('The top 10:');
// top10 looks like this: // top10 looks like this:
@@ -67,6 +68,7 @@ async function topK() {
console.log(top10); console.log(top10);
// List out the top 10 with their counts (requires RedisBloom >=2.2.9) // List out the top 10 with their counts (requires RedisBloom >=2.2.9)
// https://redis.io/commands/topk.list/
const top10WithCounts = await client.topK.listWithCount('mytopk'); const top10WithCounts = await client.topK.listWithCount('mytopk');
console.log('The top 10 with counts:'); console.log('The top 10 with counts:');
console.log(top10WithCounts); console.log(top10WithCounts);
@@ -85,6 +87,7 @@ async function topK() {
// ] // ]
// Check if a few team members are in the top 10 with TOPK.QUERY: // Check if a few team members are in the top 10 with TOPK.QUERY:
// https://redis.io/commands/topk.query/
const [ steve, suze, leibale, frederick ] = await client.topK.query('mytopk', [ const [ steve, suze, leibale, frederick ] = await client.topK.query('mytopk', [
'steve', 'steve',
'suze', 'suze',
@@ -97,7 +100,8 @@ async function topK() {
console.log(`leibale ${leibale === 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.`); console.log(`frederick ${frederick === 1 ? 'is': 'is not'} in the top 10.`);
// Get count estimate for some team members: // Get count estimate for some team members with TOPK.COUNT:
// https://redis.io/commands/topk.count/
const [ simonCount, lanceCount ] = await client.topK.count('mytopk', [ const [ simonCount, lanceCount ] = await client.topK.count('mytopk', [
'simon', 'simon',
'lance' 'lance'
@@ -107,6 +111,3 @@ async function topK() {
console.log(`Count estimate for lance: ${lanceCount}.`); console.log(`Count estimate for lance: ${lanceCount}.`);
await client.quit(); await client.quit();
}
topK();