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 `async` and `await`
* 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
* Use meaningful example data, let's not use `foo`, `bar`, `baz` etc!
* Leave an empty line at the end of your `.js` file
@@ -71,18 +71,17 @@ 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:
// <add your command(s) here, one per line>
//
// Alternatively, add code that sets up the data.
import { createClient } from 'redis';
async function doSomething() {
const client = createClient();
const client = createClient();
await client.connect();
await client.connect();
// Add your example code here...
// Add your example code here...
await client.quit();
}
await client.quit();
doSomething();
```

View File

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

View File

@@ -1,32 +1,32 @@
// 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';
async function bloomFilter() {
const client = createClient();
const client = createClient();
await client.connect();
await client.connect();
// Delete any pre-existing Bloom Filter.
await client.del('mybloom');
// Delete any pre-existing Bloom Filter.
await client.del('mybloom');
// Reserve a Bloom Filter with configurable error rate and capacity.
// https://oss.redis.com/redisbloom/Bloom_Commands/#bfreserve
try {
// Reserve a Bloom Filter with configurable error rate and capacity.
// https://redis.io/commands/bf.reserve/
try {
await client.bf.reserve('mybloom', 0.01, 1000);
console.log('Reserved Bloom Filter.');
} catch (e) {
} catch (e) {
if (e.message.endsWith('item exists')) {
console.log('Bloom Filter already reserved.');
} else {
console.log('Error, maybe RedisBloom is not installed?:');
console.log(e);
}
}
}
// Add items to Bloom Filter individually with BF.ADD command.
await Promise.all([
// Add items to Bloom Filter individually with BF.ADD command.
// https://redis.io/commands/bf.add/
await Promise.all([
client.bf.add('mybloom', 'leibale'),
client.bf.add('mybloom', 'simon'),
client.bf.add('mybloom', 'guy'),
@@ -37,43 +37,44 @@ async function bloomFilter() {
client.bf.add('mybloom', 'josefin'),
client.bf.add('mybloom', 'alex'),
client.bf.add('mybloom', 'nava'),
]);
]);
// Add multiple items to Bloom Filter at once with BF.MADD command.
await client.bf.mAdd('mybloom', [
// Add multiple items to Bloom Filter at once with BF.MADD command.
// https://redis.io/commands/bf.madd/
await client.bf.mAdd('mybloom', [
'kaitlyn',
'rachel'
]);
]);
console.log('Added members to Bloom Filter.');
console.log('Added members to Bloom Filter.');
// Check whether a member exists with the BF.EXISTS command.
const simonExists = await client.bf.exists('mybloom', 'simon');
console.log(`simon ${simonExists ? 'may' : 'does not'} exist in the Bloom Filter.`);
// Check whether a member exists with the BF.EXISTS command.
// https://redis.io/commands/bf.exists/
const simonExists = await client.bf.exists('mybloom', 'simon');
console.log(`simon ${simonExists ? 'may' : 'does not'} exist in the Bloom Filter.`);
// Check whether multiple members exist with the BF.MEXISTS command:
const [ lanceExists, leibaleExists ] = await client.bf.mExists('mybloom', [
// Check whether multiple members exist with the BF.MEXISTS command.
// https://redis.io/commands/bf.mexists/
const [ lanceExists, leibaleExists ] = await client.bf.mExists('mybloom', [
'lance',
'leibale'
]);
]);
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(`lance ${lanceExists ? '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:
const info = await client.bf.info('mybloom');
// info looks like this:
//
// {
// capacity: 1000,
// size: 1531,
// numberOfFilters: 1,
// numberOfInsertedItems: 12,
// expansionRate: 2
// }
console.log(info);
// Get stats for the Bloom Filter with the BF.INFO command.
// https://redis.io/commands/bf.info/
const info = await client.bf.info('mybloom');
// info looks like this:
//
// {
// capacity: 1000,
// size: 1531,
// numberOfFilters: 1,
// numberOfInsertedItems: 12,
// expansionRate: 2
// }
console.log(info);
await client.quit();
}
bloomFilter();
await client.quit();

View File

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

View File

@@ -7,24 +7,20 @@
import { createClient } from 'redis';
async function connectWithACLUser() {
const client = createClient({
const client = createClient({
url: 'redis://testuser:testpassword@127.0.0.1:6379'
});
});
await client.connect();
await client.connect();
// Returns PONG
console.log(`Response from PING command: ${await client.ping()}`);
// Returns PONG
console.log(`Response from PING command: ${await client.ping()}`);
try {
try {
// This will error as this user is not allowed to run this command...
console.log(`Response from GET command: ${await client.get('somekey')}`);
} catch (e) {
} catch (e) {
console.log(`GET command failed: ${e.message}`);
}
await client.quit();
}
connectWithACLUser();
await client.quit();

View File

@@ -1,27 +1,26 @@
// 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';
async function countMinSketch() {
const client = createClient();
const client = createClient();
await client.connect();
await client.connect();
// Delete any pre-existing Count-Min Sketch.
await client.del('mycms');
// Delete any pre-existing Count-Min Sketch.
await client.del('mycms');
// Initialize a Count-Min Sketch with error rate and probability:
// https://oss.redis.com/redisbloom/CountMinSketch_Commands/#cmsinitbyprob
try {
// 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('Initialized Count-Min Sketch.');
} catch (e) {
console.log('Reserved Count Min Sketch.');
} catch (e) {
console.log('Error, maybe RedisBloom is not installed?:');
console.log(e);
}
}
const teamMembers = [
const teamMembers = [
'leibale',
'simon',
'guy',
@@ -36,13 +35,14 @@ async function countMinSketch() {
'lance',
'rachel',
'kaitlyn'
];
];
// Store actual counts for comparison with CMS.
let actualCounts = {};
// Store actual counts for comparison with CMS.
let actualCounts = {};
// Randomly emit a team member and count them with the CMS.
for (let n = 0; n < 1000; n++) {
// 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,
@@ -52,32 +52,29 @@ async function countMinSketch() {
actualCounts[teamMember] = actualCounts[teamMember] ? actualCounts[teamMember] + 1 : 1;
console.log(`Incremented score for ${teamMember}.`);
}
// Get count estimate for some team members:
// https://oss.redis.com/redisbloom/CountMinSketch_Commands/#cmsquery
const [ alexCount, rachelCount ] = await client.cms.query('mycms', [
'simon',
'lance'
]);
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://oss.redis.com/redisbloom/CountMinSketch_Commands/#cmsinfo
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();
}
countMinSketch();
// 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();

View File

@@ -1,29 +1,28 @@
// 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';
async function cuckooFilter() {
const client = createClient();
const client = createClient();
await client.connect();
await client.connect();
// Delete any pre-existing Cuckoo Filter.
await client.del('mycuckoo');
// Delete any pre-existing Cuckoo Filter.
await client.del('mycuckoo');
// Reserve a Cuckoo Filter with a capacity of 10000 items.
// https://oss.redis.com/redisbloom/Cuckoo_Commands/#cfreserve
try {
// Reserve a Cuckoo Filter with a capacity of 10000 items.
// https://redis.io/commands/cf.reserve/
try {
await client.cf.reserve('mycuckoo', 10000);
console.log('Reserved Cuckoo Filter.');
} catch (e) {
} catch (e) {
console.log('Error, maybe RedisBloom is not installed?:');
console.log(e);
}
}
// Add items to Cuckoo Filter individually with CF.ADD command.
https://oss.redis.com/redisbloom/Cuckoo_Commands/#cfadd
await Promise.all([
// Add items to Cuckoo Filter individually with CF.ADD command.
// https://redis.io/commands/cf.add/
await Promise.all([
client.cf.add('mycuckoo', 'leibale'),
client.cf.add('mycuckoo', 'simon'),
client.cf.add('mycuckoo', 'guy'),
@@ -34,48 +33,47 @@ async function cuckooFilter() {
client.cf.add('mycuckoo', 'josefin'),
client.cf.add('mycuckoo', 'alex'),
client.cf.add('mycuckoo', 'nava'),
]);
]);
// Add items to the Cuckoo Filter only if they don't exist in it...
// https://oss.redis.com/redisbloom/Cuckoo_Commands/#cfaddnx
const nxReply = await Promise.all([
// Add items to the Cuckoo Filter only if they don't exist in it...
// https://redis.io/commands/cf.addnx/
const nxReply = await Promise.all([
client.cf.addNX('mycuckoo', 'kaitlyn'), // New
client.cf.addNX('mycuckoo', 'rachel'), // New
client.cf.addNX('mycuckoo', 'brian') // Previously added
]);
]);
console.log('Added members to Cuckoo Filter.');
console.log('nxReply:');
console.log('Added members to Cuckoo Filter.');
console.log('nxReply:');
// nxReply looks like this:
// [
// true,
// true,
// false
// ]
console.log(nxReply);
// nxReply looks like this:
// [
// true,
// true,
// false
// ]
console.log(nxReply);
// Check whether a member exists with the CF.EXISTS command.
const simonExists = await client.bf.exists('mycuckoo', 'simon');
console.log(`simon ${simonExists ? 'may' : 'does not'} exist in the Cuckoo Filter.`);
// Check whether a member exists with the CF.EXISTS command.
// https://redis.io/commands/cf.exists/
const simonExists = await client.bf.exists('mycuckoo', 'simon');
console.log(`simon ${simonExists ? 'may' : 'does not'} exist in the Cuckoo Filter.`);
// Get stats for the Cuckoo Filter with the CF.INFO command:
const info = await client.cf.info('mycuckoo');
// Get stats for the Cuckoo Filter with the CF.INFO command:
// https://redis.io/commands/cf.info/
const info = await client.cf.info('mycuckoo');
// info looks like this:
// {
// size: 16440,
// numberOfBuckets: 8192,
// numberOfFilters: 1,
// numberOfInsertedItems: 12,
// numberOfDeletedItems: 0,
// bucketSize: 2,
// expansionRate: 1,
// maxIteration: 20
// }
console.log(info);
// info looks like this:
// {
// size: 16440,
// numberOfBuckets: 8192,
// numberOfFilters: 1,
// numberOfInsertedItems: 12,
// numberOfDeletedItems: 0,
// bucketSize: 2,
// expansionRate: 1,
// maxIteration: 20
// }
console.log(info);
await client.quit();
}
cuckooFilter();
await client.quit();

View File

@@ -2,15 +2,11 @@
import { createClient } from 'redis';
async function getServerTime() {
const client = createClient();
await client.connect();
const client = createClient();
await client.connect();
const serverTime = await client.time();
// 2022-02-25T12:57:40.000Z { microseconds: 351346 }
console.log(serverTime);
const serverTime = await client.time();
// 2022-02-25T12:57:40.000Z { microseconds: 351346 }
console.log(serverTime);
await client.quit();
}
getServerTime();
await client.quit();

View File

@@ -3,8 +3,7 @@
import { createClient, defineScript } from 'redis';
async function luaMultiIncr() {
const client = createClient({
const client = createClient({
scripts: {
mincr: defineScript({
NUMBER_OF_KEYS: 2,
@@ -18,14 +17,11 @@ async function luaMultiIncr() {
},
}),
},
});
});
await client.connect();
await client.connect();
await client.set('mykey', '5');
console.log(await client.mincr('mykey', 'myotherkey', 10)); // [ 15, 10 ]
await client.set('mykey', '5');
console.log(await client.mincr('mykey', 'myotherkey', 10)); // [ 15, 10 ]
await client.quit();
}
luaMultiIncr();
await client.quit();

View File

@@ -2,14 +2,13 @@
import { createClient } from 'redis';
async function managingJSON() {
const client = createClient();
const client = createClient();
await client.connect();
await client.del('noderedis:jsondata');
await client.connect();
await client.del('noderedis:jsondata');
// Store a JSON object...
await client.json.set('noderedis:jsondata', '$', {
// Store a JSON object...
await client.json.set('noderedis:jsondata', '$', {
name: 'Roberta McDonald',
pets: [
{
@@ -38,44 +37,40 @@ async function managingJSON() {
state: 'OH',
country: 'USA'
}
});
});
// Retrieve the name and age of the second pet in the pets array.
let results = await client.json.get('noderedis:jsondata', {
// Retrieve the name and age of the second pet in the pets array.
let results = await client.json.get('noderedis:jsondata', {
path: [
'.pets[1].name',
'.pets[1].age'
'$.pets[1].name',
'$.pets[1].age'
]
});
});
// { '.pets[1].name': 'Rex', '.pets[1].age': 3 }
console.log(results);
// { '$.pets[1].name': [ 'Rex' ], '$.pets[1].age': [ 3 ] }
console.log(results);
// Goldie had a birthday, increment the age...
await client.json.numIncrBy('noderedis:jsondata', '.pets[2].age', 1);
results = await client.json.get('noderedis:jsondata', {
path: '.pets[2].age'
});
// Goldie had a birthday, increment the age...
await client.json.numIncrBy('noderedis:jsondata', '$.pets[2].age', 1);
results = await client.json.get('noderedis:jsondata', {
path: '$.pets[2].age'
});
// Goldie is 3 years old now.
console.log(`Goldie is ${JSON.stringify(results)} years old now.`);
// Goldie is 3 years old now.
console.log(`Goldie is ${JSON.stringify(results[0])} years old now.`);
// Add a new pet...
await client.json.arrAppend('noderedis:jsondata', '.pets', {
// Add a new pet...
await client.json.arrAppend('noderedis:jsondata', '$.pets', {
name: 'Robin',
species: 'bird',
isMammal: false,
age: 1
});
});
// How many pets do we have now?
const numPets = await client.json.arrLen('noderedis:jsondata', '.pets');
// How many pets do we have now?
const numPets = await client.json.arrLen('noderedis:jsondata', '$.pets');
// We now have 4 pets.
console.log(`We now have ${numPets} pets.`);
await client.quit();
}
managingJSON();
// We now have 4 pets.
console.log(`We now have ${numPets} pets.`);
await client.quit();

View File

@@ -3,14 +3,13 @@
import { createClient, SchemaFieldTypes } from 'redis';
async function searchHashes() {
const client = createClient();
const client = createClient();
await client.connect();
await client.connect();
// Create an index...
try {
// Documentation: https://oss.redis.com/redisearch/Commands/#ftcreate
// Create an index...
try {
// Documentation: https://redis.io/commands/ft.create/
await client.ft.create('idx:animals', {
name: {
type: SchemaFieldTypes.TEXT,
@@ -22,7 +21,7 @@ async function searchHashes() {
ON: 'HASH',
PREFIX: 'noderedis:animals'
});
} catch (e) {
} catch (e) {
if (e.message === 'Index already exists') {
console.log('Index exists already, skipped creation.');
} else {
@@ -30,62 +29,60 @@ async function searchHashes() {
console.error(e);
process.exit(1);
}
}
}
// Add some sample data...
await Promise.all([
// Add some sample data...
// https://redis.io/commands/hset/
await Promise.all([
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:3', {name: 'Rover', species: 'dog', age: 9}),
client.hSet('noderedis:animals:4', {name: 'Fido', species: 'dog', age: 7})
]);
]);
// Perform a search query, find all the dogs... sort by age, descending.
// Documentation: https://oss.redis.com/redisearch/Commands/#ftsearch
// Query syntax: https://oss.redis.com/redisearch/Query_Syntax/
const results = await client.ft.search(
// Perform a search query, find all the dogs... sort by age, descending.
// Documentation: https://redis.io/commands/ft.search/
// Query syntax: https://redis.io/docs/stack/search/reference/query_syntax/
const results = await client.ft.search(
'idx:animals',
'@species:{dog}',
{
SORTBY: {
BY: 'age',
DIRECTION: 'DESC' // or 'ASC' (default if DIRECTION is not present)
DIRECTION: 'DESC' // or 'ASC (default if DIRECTION is not present)
}
}
);
);
// results:
// {
// total: 2,
// documents: [
// {
// id: 'noderedis:animals:3',
// value: {
// age: '9',
// name: 'Rover',
// species: 'dog'
// }
// },
// {
// id: 'noderedis:animals:4',
// value: {
// age: '7',
// name: 'Fido',
// species: 'dog'
// }
// }
// ]
// }
// results:
// {
// total: 2,
// documents: [
// {
// id: 'noderedis:animals:3',
// value: {
// name: 'Rover',
// species: 'dog',
// age: '9'
// }
// },
// {
// id: 'noderedis:animals:4',
// value: {
// name: 'Fido',
// species: 'dog',
// age: '7'
// }
// }
// ]
// }
console.log(`Results found: ${results.total}.`);
console.log(`Results found: ${results.total}.`);
for (const doc of results.documents) {
for (const doc of results.documents) {
// noderedis:animals:3: Rover, 9 years old.
// noderedis:animals:4: Fido, 7 years old.
console.log(`${doc.id}: ${doc.value.name}, ${doc.value.age} years old.`);
}
await client.quit();
}
searchHashes();
await client.quit();

View File

@@ -1,14 +1,17 @@
// 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';
async function searchJSON() {
const client = createClient();
const client = createClient();
await client.connect();
await client.connect();
// Create an index.
try {
// Create an index.
// https://redis.io/commands/ft.create/
try {
await client.ft.create('idx:users', {
'$.name': {
type: SchemaFieldTypes.TEXT,
@@ -30,7 +33,7 @@ async function searchJSON() {
ON: 'JSON',
PREFIX: 'noderedis:users'
});
} catch (e) {
} catch (e) {
if (e.message === 'Index already exists') {
console.log('Index exists already, skipped creation.');
} else {
@@ -38,10 +41,11 @@ async function searchJSON() {
console.error(e);
process.exit(1);
}
}
}
// Add some users.
await Promise.all([
// Add some users.
// https://redis.io/commands/json.set/
await Promise.all([
client.json.set('noderedis:users:1', '$', {
name: 'Alice',
age: 32,
@@ -54,64 +58,64 @@ async function searchJSON() {
coins: 15,
email: 'bob@somewhere.gov'
})
]);
]);
// Search all users under 30
console.log('Users under 30 years old:');
console.log(
// https://oss.redis.com/redisearch/Commands/#ftsearch
// Search all users under 30
console.log('Users under 30 years old:');
console.log(
// https://redis.io/commands/ft.search/
JSON.stringify(
await client.ft.search('idx:users', '@age:[0 30]'),
null,
2
)
);
// {
// "total": 1,
// "documents": [
// {
// "id": "noderedis:users:2",
// "value": {
// "name": "Bob",
// "age": 23,
// "coins": 15,
// "email": "bob@somewhere.gov"
// }
// }
// ]
// }
);
// {
// "total": 1,
// "documents": [
// {
// "id": "noderedis:users:2",
// "value": {
// "name": "Bob",
// "age": 23,
// "coins": 15,
// "email": "bob@somewhere.gov"
// }
// }
// ]
// }
// Find a user by email - note we need to escape . and @ characters
// in the email address. This applies for other punctuation too.
// https://oss.redis.com/redisearch/Tags/#including_punctuation_in_tags
console.log('Users with email "bob@somewhere.gov":');
const emailAddress = 'bob@somewhere.gov'.replace(/[.@]/g, '\\$&');
console.log(
// Find a user by email - note we need to escape . and @ characters
// in the email address. This applies for other punctuation too.
// https://redis.io/docs/stack/search/reference/tags/#including-punctuation-in-tags
console.log('Users with email "bob@somewhere.gov":');
const emailAddress = 'bob@somewhere.gov'.replace(/[.@]/g, '\\$&');
console.log(
JSON.stringify(
await client.ft.search('idx:users', `@email:{${emailAddress}}`),
null,
2
)
);
// {
// "total": 1,
// "documents": [
// {
// "id": "noderedis:users:2",
// "value": {
// "name": "Bob",
// "age": 23,
// "coins": 15,
// "email": "bob@somewhere.gov"
// }
// }
// ]
// }
);
// {
// "total": 1,
// "documents": [
// {
// "id": "noderedis:users:2",
// "value": {
// "name": "Bob",
// "age": 23,
// "coins": 15,
// "email": "bob@somewhere.gov"
// }
// }
// ]
// }
// Some aggregrations, what's the average age and total number of coins...
// https://oss.redis.com/redisearch/Commands/#ftaggregate
console.log('Aggregation Demo:');
console.log(
// Some aggregrations, what's the average age and total number of coins...
// https://redis.io/commands/ft.aggregate/
console.log('Aggregation Demo:');
console.log(
JSON.stringify(
await client.ft.aggregate('idx:users', '*', {
STEPS: [{
@@ -130,18 +134,15 @@ async function searchJSON() {
null,
2
)
);
// {
// "total": 1,
// "results": [
// {
// "averageAge": "27.5",
// "totalCoins": "115"
// }
// ]
// }
);
// {
// "total": 1,
// "results": [
// {
// "averageAge": "27.5",
// "totalCoins": "115"
// }
// ]
// }
await client.quit();
}
searchJSON();
await client.quit();

View File

@@ -4,16 +4,12 @@
import { createClient } from 'redis';
async function setScan() {
const client = createClient();
await client.connect();
const client = createClient();
await client.connect();
const setName = 'setName';
for await (const member of client.sScanIterator(setName)) {
const setName = 'setName';
for await (const member of client.sScanIterator(setName)) {
console.log(member);
}
await client.quit();
}
setScan();
await client.quit();

View File

@@ -3,11 +3,10 @@
import { createClient } from 'redis';
async function addToSortedSet() {
const client = createClient();
await client.connect();
const client = createClient();
await client.connect();
await client.zAdd('mysortedset', [
await client.zAdd('mysortedset', [
{
score: 99,
value: 'Ninety Nine'
@@ -20,16 +19,13 @@ async function addToSortedSet() {
score: 101,
value: 'One Hundred and One'
}
]);
]);
// Get all of the values/scores from the sorted set using
// the scan approach:
// https://redis.io/commands/zscan
for await (const memberWithScore of client.zScanIterator('mysortedset')) {
// Get all of the values/scores from the sorted set using
// the scan approach:
// https://redis.io/commands/zscan
for await (const memberWithScore of client.zScanIterator('mysortedset')) {
console.log(memberWithScore);
}
await client.quit();
}
addToSortedSet();
await client.quit();

View File

@@ -1,4 +1,6 @@
// 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
// in the same consumer group such that the group as a whole receives
// every entry from the stream.
@@ -20,32 +22,33 @@
import { createClient, commandOptions } from 'redis';
async function streamConsumerGroup() {
const client = createClient();
const client = createClient();
if (process.argv.length !== 3) {
if (process.argv.length !== 3) {
console.log(`usage: node stream-consumer-group.js <consumerName>`);
process.exit(1);
}
}
const consumerName = process.argv[2];
const consumerName = process.argv[2];
await client.connect();
await client.connect();
// Create the consumer group (and stream) if needed...
try {
// Create the consumer group (and stream) if needed...
try {
// https://redis.io/commands/xgroup-create/
await client.xGroupCreate('mystream', 'myconsumergroup', '0', {
MKSTREAM: true
});
console.log('Created consumer group.');
} catch (e) {
} catch (e) {
console.log('Consumer group already exists, skipped creation.');
}
}
console.log(`Starting consumer ${consumerName}.`);
console.log(`Starting consumer ${consumerName}.`);
while (true) {
while (true) {
try {
// https://redis.io/commands/xreadgroup/
let response = await client.xReadGroup(
commandOptions({
isolated: true
@@ -86,6 +89,7 @@ async function streamConsumerGroup() {
// Use XACK to acknowledge successful processing of this
// stream entry.
// https://redis.io/commands/xack/
const entryId = response[0].messages[0].id;
await client.xAck('mystream', 'myconsumergroup', entryId);
@@ -98,7 +102,4 @@ async function streamConsumerGroup() {
} catch (err) {
console.error(err);
}
}
}
streamConsumerGroup();

View File

@@ -1,16 +1,16 @@
// 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
import { createClient, commandOptions } from 'redis';
async function streamConsumer() {
const client = createClient();
const client = createClient();
await client.connect();
await client.connect();
let currentId = '0-0'; // Start at lowest possible stream ID
let currentId = '0-0'; // Start at lowest possible stream ID
while (true) {
while (true) {
try {
let response = await client.xRead(
commandOptions({
@@ -58,7 +58,4 @@ async function streamConsumer() {
} catch (err) {
console.error(err);
}
}
}
streamConsumer();

View File

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

View File

@@ -1,18 +1,17 @@
// 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 { TimeSeriesDuplicatePolicies, TimeSeriesEncoding, TimeSeriesAggregationType } from '@redis/time-series';
async function timeSeries() {
const client = createClient();
const client = createClient();
await client.connect();
await client.del('mytimeseries');
await client.connect();
await client.del('mytimeseries');
try {
try {
// Create a timeseries
// https://oss.redis.com/redistimeseries/commands/#tscreate
// https://redis.io/commands/ts.create/
const created = await client.ts.create('mytimeseries', {
RETENTION: 86400000, // 1 day in milliseconds
ENCODING: TimeSeriesEncoding.UNCOMPRESSED, // No compression
@@ -32,7 +31,7 @@ async function timeSeries() {
while (num < 10000) {
// 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);
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:
// https://oss.redis.com/redistimeseries/commands/#tsmadd
// https://redis.io/commands/ts.madd/
const response = await client.ts.mAdd([{
key: 'mytimeseries',
timestamp: currentTimestamp + 60000,
@@ -59,7 +58,7 @@ async function timeSeries() {
}
// 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', {
RETENTION: 0 // Keep the entries forever
});
@@ -69,7 +68,7 @@ async function timeSeries() {
}
// 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 toTimestamp = 1640995260000; // Jan 1 2022 00:01:00
const rangeResponse = await client.ts.range('mytimeseries', fromTimestamp, toTimestamp, {
@@ -95,7 +94,7 @@ async function timeSeries() {
console.log(rangeResponse);
// 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');
// tsInfo looks like this:
@@ -116,11 +115,8 @@ async function timeSeries() {
console.log('Timeseries info:');
console.log(tsInfo);
} catch (e) {
} catch (e) {
console.error(e);
}
await client.quit();
}
timeSeries();
await client.quit();

View File

@@ -1,31 +1,30 @@
// 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';
async function topK() {
const client = createClient();
const client = createClient();
await client.connect();
await client.connect();
// Delete any pre-existing Top K.
await client.del('mytopk');
// 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);
// Reserve a Top K to track the 10 most common items.
// https://redis.io/commands/topk.reserve/
try {
await client.topK.reserve('mytopk', 10, { width: 400, depth: 10, decay: 0.9 });
console.log('Reserved Top K.');
} catch (e) {
} 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 = [
const teamMembers = [
'leibale',
'simon',
'guy',
@@ -40,10 +39,11 @@ async function topK() {
'lance',
'rachel',
'kaitlyn'
];
];
// Add random counts for random team members with TOPK.INCRBY
for (let n = 0; n < 1000; n++) {
// Add random counts for random team members with TOPK.INCRBY
// https://redis.io/commands/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', {
@@ -51,62 +51,63 @@ async function topK() {
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);
// List out the top 10 with TOPK.LIST
// https://redis.io/commands/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);
// List out the top 10 with their counts (requires RedisBloom >=2.2.9)
const top10WithCounts = await client.topK.listWithCount('mytopk');
console.log('The top 10 with counts:');
console.log(top10WithCounts);
// top10WithCounts looks like this:
// [
// { item: 'suze', count: 42363 },
// { item: 'lance', count: 41982 },
// { item: 'simon', count: 41831 },
// { item: 'steve', count: 39237 },
// { item: 'guy', count: 39078 },
// { item: 'kyleb', count: 37338 },
// { item: 'leibale', count: 34230 },
// { item: 'kyleo', count: 33812 },
// { item: 'alex', count: 33679 },
// { item: 'nava', count: 32663 }
// ]
// 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');
console.log('The top 10 with counts:');
console.log(top10WithCounts);
// top10WithCounts looks like this:
// [
// { item: 'suze', count: 42363 },
// { item: 'lance', count: 41982 },
// { item: 'simon', count: 41831 },
// { item: 'steve', count: 39237 },
// { item: 'guy', count: 39078 },
// { item: 'kyleb', count: 37338 },
// { item: 'leibale', count: 34230 },
// { item: 'kyleo', count: 33812 },
// { item: 'alex', count: 33679 },
// { item: 'nava', count: 32663 }
// ]
// Check if a few team members are in the top 10 with TOPK.QUERY:
const [ steve, suze, leibale, frederick ] = await client.topK.query('mytopk', [
// 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', [
'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.`);
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', [
// Get count estimate for some team members with TOPK.COUNT:
// https://redis.io/commands/topk.count/
const [ simonCount, lanceCount ] = await client.topK.count('mytopk', [
'simon',
'lance'
]);
]);
console.log(`Count estimate for simon: ${simonCount}.`);
console.log(`Count estimate for lance: ${lanceCount}.`);
console.log(`Count estimate for simon: ${simonCount}.`);
console.log(`Count estimate for lance: ${lanceCount}.`);
await client.quit();
}
topK();
await client.quit();