You've already forked node-redis
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:
@@ -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,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:
|
||||
// <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();
|
||||
|
||||
await client.connect();
|
||||
@@ -82,7 +83,5 @@ async function doSomething() {
|
||||
// Add your example code here...
|
||||
|
||||
await client.quit();
|
||||
}
|
||||
|
||||
doSomething();
|
||||
```
|
||||
|
@@ -6,7 +6,6 @@
|
||||
|
||||
import { createClient, commandOptions } from 'redis';
|
||||
|
||||
async function blockingListPop() {
|
||||
const client = createClient();
|
||||
|
||||
await client.connect();
|
||||
@@ -21,12 +20,11 @@ async function blockingListPop() {
|
||||
|
||||
await client.lPush(keyName, 'value');
|
||||
|
||||
await blpopPromise;
|
||||
const listItem = await blpopPromise;
|
||||
|
||||
console.log('blpopPromise resolved');
|
||||
console.log(keyName);
|
||||
// listItem will be:
|
||||
// {"key":"keyName","element":"value"}
|
||||
console.log(`listItem is '${JSON.stringify(listItem)}'`);
|
||||
|
||||
await client.quit();
|
||||
}
|
||||
|
||||
blockingListPop();
|
||||
|
@@ -1,9 +1,8 @@
|
||||
// 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();
|
||||
|
||||
await client.connect();
|
||||
@@ -12,7 +11,7 @@ async function bloomFilter() {
|
||||
await client.del('mybloom');
|
||||
|
||||
// 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 {
|
||||
await client.bf.reserve('mybloom', 0.01, 1000);
|
||||
console.log('Reserved Bloom Filter.');
|
||||
@@ -26,6 +25,7 @@ async function bloomFilter() {
|
||||
}
|
||||
|
||||
// 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'),
|
||||
@@ -40,6 +40,7 @@ async function bloomFilter() {
|
||||
]);
|
||||
|
||||
// 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'
|
||||
@@ -48,10 +49,12 @@ async function bloomFilter() {
|
||||
console.log('Added members to 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:
|
||||
// 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'
|
||||
@@ -60,7 +63,8 @@ async function bloomFilter() {
|
||||
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:
|
||||
// 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:
|
||||
//
|
||||
@@ -74,6 +78,3 @@ async function bloomFilter() {
|
||||
console.log(info);
|
||||
|
||||
await client.quit();
|
||||
}
|
||||
|
||||
bloomFilter();
|
||||
|
@@ -3,7 +3,6 @@
|
||||
|
||||
import { createClient } from 'redis';
|
||||
|
||||
async function commandWithModifiers() {
|
||||
const client = createClient();
|
||||
|
||||
await client.connect();
|
||||
@@ -14,7 +13,7 @@ async function commandWithModifiers() {
|
||||
GET: true
|
||||
});
|
||||
|
||||
console.log(result); //nil
|
||||
console.log(result); //null
|
||||
|
||||
result = await client.set('mykey', 'newvalue', {
|
||||
EX: 60,
|
||||
@@ -24,7 +23,3 @@ async function commandWithModifiers() {
|
||||
console.log(result); //myvalue
|
||||
|
||||
await client.quit();
|
||||
}
|
||||
|
||||
commandWithModifiers();
|
||||
|
||||
|
@@ -7,7 +7,6 @@
|
||||
|
||||
import { createClient } from 'redis';
|
||||
|
||||
async function connectWithACLUser() {
|
||||
const client = createClient({
|
||||
url: 'redis://testuser:testpassword@127.0.0.1:6379'
|
||||
});
|
||||
@@ -25,6 +24,3 @@ async function connectWithACLUser() {
|
||||
}
|
||||
|
||||
await client.quit();
|
||||
}
|
||||
|
||||
connectWithACLUser();
|
||||
|
@@ -1,9 +1,8 @@
|
||||
// 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();
|
||||
|
||||
await client.connect();
|
||||
@@ -12,10 +11,10 @@ async function countMinSketch() {
|
||||
await client.del('mycms');
|
||||
|
||||
// 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 {
|
||||
await client.cms.initByProb('mycms', 0.001, 0.01);
|
||||
console.log('Initialized Count-Min Sketch.');
|
||||
console.log('Reserved Count Min Sketch.');
|
||||
} catch (e) {
|
||||
console.log('Error, maybe RedisBloom is not installed?:');
|
||||
console.log(e);
|
||||
@@ -42,6 +41,7 @@ async function countMinSketch() {
|
||||
let actualCounts = {};
|
||||
|
||||
// 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', {
|
||||
@@ -55,17 +55,17 @@ async function countMinSketch() {
|
||||
}
|
||||
|
||||
// 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', [
|
||||
'simon',
|
||||
'lance'
|
||||
'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://oss.redis.com/redisbloom/CountMinSketch_Commands/#cmsinfo
|
||||
// https://redis.io/commands/cms.info/
|
||||
const info = await client.cms.info('mycms');
|
||||
console.log('Count-Min Sketch info:');
|
||||
|
||||
@@ -78,6 +78,3 @@ async function countMinSketch() {
|
||||
console.log(info);
|
||||
|
||||
await client.quit();
|
||||
}
|
||||
|
||||
countMinSketch();
|
||||
|
@@ -1,9 +1,8 @@
|
||||
// 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();
|
||||
|
||||
await client.connect();
|
||||
@@ -12,7 +11,7 @@ async function cuckooFilter() {
|
||||
await client.del('mycuckoo');
|
||||
|
||||
// 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 {
|
||||
await client.cf.reserve('mycuckoo', 10000);
|
||||
console.log('Reserved Cuckoo Filter.');
|
||||
@@ -22,7 +21,7 @@ async function cuckooFilter() {
|
||||
}
|
||||
|
||||
// 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([
|
||||
client.cf.add('mycuckoo', 'leibale'),
|
||||
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...
|
||||
// https://oss.redis.com/redisbloom/Cuckoo_Commands/#cfaddnx
|
||||
// https://redis.io/commands/cf.addnx/
|
||||
const nxReply = await Promise.all([
|
||||
client.cf.addNX('mycuckoo', 'kaitlyn'), // New
|
||||
client.cf.addNX('mycuckoo', 'rachel'), // New
|
||||
@@ -56,10 +55,12 @@ async function cuckooFilter() {
|
||||
console.log(nxReply);
|
||||
|
||||
// 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:
|
||||
// https://redis.io/commands/cf.info/
|
||||
const info = await client.cf.info('mycuckoo');
|
||||
|
||||
// info looks like this:
|
||||
@@ -76,6 +77,3 @@ async function cuckooFilter() {
|
||||
console.log(info);
|
||||
|
||||
await client.quit();
|
||||
}
|
||||
|
||||
cuckooFilter();
|
||||
|
@@ -2,7 +2,6 @@
|
||||
|
||||
import { createClient } from 'redis';
|
||||
|
||||
async function getServerTime() {
|
||||
const client = createClient();
|
||||
await client.connect();
|
||||
|
||||
@@ -11,6 +10,3 @@ async function getServerTime() {
|
||||
console.log(serverTime);
|
||||
|
||||
await client.quit();
|
||||
}
|
||||
|
||||
getServerTime();
|
||||
|
@@ -3,7 +3,6 @@
|
||||
|
||||
import { createClient, defineScript } from 'redis';
|
||||
|
||||
async function luaMultiIncr() {
|
||||
const client = createClient({
|
||||
scripts: {
|
||||
mincr: defineScript({
|
||||
@@ -26,6 +25,3 @@ async function luaMultiIncr() {
|
||||
console.log(await client.mincr('mykey', 'myotherkey', 10)); // [ 15, 10 ]
|
||||
|
||||
await client.quit();
|
||||
}
|
||||
|
||||
luaMultiIncr();
|
||||
|
@@ -2,7 +2,6 @@
|
||||
|
||||
import { createClient } from 'redis';
|
||||
|
||||
async function managingJSON() {
|
||||
const client = createClient();
|
||||
|
||||
await client.connect();
|
||||
@@ -43,25 +42,25 @@ async function managingJSON() {
|
||||
// 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 }
|
||||
// { '$.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);
|
||||
await client.json.numIncrBy('noderedis:jsondata', '$.pets[2].age', 1);
|
||||
results = await client.json.get('noderedis:jsondata', {
|
||||
path: '.pets[2].age'
|
||||
path: '$.pets[2].age'
|
||||
});
|
||||
|
||||
// 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...
|
||||
await client.json.arrAppend('noderedis:jsondata', '.pets', {
|
||||
await client.json.arrAppend('noderedis:jsondata', '$.pets', {
|
||||
name: 'Robin',
|
||||
species: 'bird',
|
||||
isMammal: false,
|
||||
@@ -69,13 +68,9 @@ async function managingJSON() {
|
||||
});
|
||||
|
||||
// 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.
|
||||
console.log(`We now have ${numPets} pets.`);
|
||||
|
||||
await client.quit();
|
||||
}
|
||||
|
||||
managingJSON();
|
||||
|
||||
|
@@ -3,14 +3,13 @@
|
||||
|
||||
import { createClient, SchemaFieldTypes } from 'redis';
|
||||
|
||||
async function searchHashes() {
|
||||
const client = createClient();
|
||||
|
||||
await client.connect();
|
||||
|
||||
// Create an index...
|
||||
try {
|
||||
// Documentation: https://oss.redis.com/redisearch/Commands/#ftcreate
|
||||
// Documentation: https://redis.io/commands/ft.create/
|
||||
await client.ft.create('idx:animals', {
|
||||
name: {
|
||||
type: SchemaFieldTypes.TEXT,
|
||||
@@ -33,6 +32,7 @@ async function searchHashes() {
|
||||
}
|
||||
|
||||
// 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}),
|
||||
@@ -41,15 +41,15 @@ async function searchHashes() {
|
||||
]);
|
||||
|
||||
// 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/
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -61,17 +61,17 @@ async function searchHashes() {
|
||||
// {
|
||||
// id: 'noderedis:animals:3',
|
||||
// value: {
|
||||
// age: '9',
|
||||
// name: 'Rover',
|
||||
// species: 'dog'
|
||||
// species: 'dog',
|
||||
// age: '9'
|
||||
// }
|
||||
// },
|
||||
// {
|
||||
// id: 'noderedis:animals:4',
|
||||
// value: {
|
||||
// age: '7',
|
||||
// name: 'Fido',
|
||||
// species: 'dog'
|
||||
// species: 'dog',
|
||||
// age: '7'
|
||||
// }
|
||||
// }
|
||||
// ]
|
||||
@@ -86,6 +86,3 @@ async function searchHashes() {
|
||||
}
|
||||
|
||||
await client.quit();
|
||||
}
|
||||
|
||||
searchHashes();
|
||||
|
@@ -1,13 +1,16 @@
|
||||
// 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();
|
||||
|
||||
await client.connect();
|
||||
|
||||
// Create an index.
|
||||
// https://redis.io/commands/ft.create/
|
||||
try {
|
||||
await client.ft.create('idx:users', {
|
||||
'$.name': {
|
||||
@@ -41,6 +44,7 @@ async function searchJSON() {
|
||||
}
|
||||
|
||||
// Add some users.
|
||||
// https://redis.io/commands/json.set/
|
||||
await Promise.all([
|
||||
client.json.set('noderedis:users:1', '$', {
|
||||
name: 'Alice',
|
||||
@@ -59,7 +63,7 @@ async function searchJSON() {
|
||||
// Search all users under 30
|
||||
console.log('Users under 30 years old:');
|
||||
console.log(
|
||||
// https://oss.redis.com/redisearch/Commands/#ftsearch
|
||||
// https://redis.io/commands/ft.search/
|
||||
JSON.stringify(
|
||||
await client.ft.search('idx:users', '@age:[0 30]'),
|
||||
null,
|
||||
@@ -83,7 +87,7 @@ async function searchJSON() {
|
||||
|
||||
// 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
|
||||
// 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(
|
||||
@@ -109,7 +113,7 @@ async function searchJSON() {
|
||||
// }
|
||||
|
||||
// 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(
|
||||
JSON.stringify(
|
||||
@@ -142,6 +146,3 @@ async function searchJSON() {
|
||||
// }
|
||||
|
||||
await client.quit();
|
||||
}
|
||||
|
||||
searchJSON();
|
||||
|
@@ -4,7 +4,6 @@
|
||||
|
||||
import { createClient } from 'redis';
|
||||
|
||||
async function setScan() {
|
||||
const client = createClient();
|
||||
await client.connect();
|
||||
|
||||
@@ -14,6 +13,3 @@ async function setScan() {
|
||||
}
|
||||
|
||||
await client.quit();
|
||||
}
|
||||
|
||||
setScan();
|
||||
|
@@ -3,7 +3,6 @@
|
||||
|
||||
import { createClient } from 'redis';
|
||||
|
||||
async function addToSortedSet() {
|
||||
const client = createClient();
|
||||
await client.connect();
|
||||
|
||||
@@ -30,6 +29,3 @@ async function addToSortedSet() {
|
||||
}
|
||||
|
||||
await client.quit();
|
||||
}
|
||||
|
||||
addToSortedSet();
|
||||
|
@@ -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,7 +22,6 @@
|
||||
|
||||
import { createClient, commandOptions } from 'redis';
|
||||
|
||||
async function streamConsumerGroup() {
|
||||
const client = createClient();
|
||||
|
||||
if (process.argv.length !== 3) {
|
||||
@@ -34,6 +35,7 @@ async function streamConsumerGroup() {
|
||||
|
||||
// Create the consumer group (and stream) if needed...
|
||||
try {
|
||||
// https://redis.io/commands/xgroup-create/
|
||||
await client.xGroupCreate('mystream', 'myconsumergroup', '0', {
|
||||
MKSTREAM: true
|
||||
});
|
||||
@@ -46,6 +48,7 @@ async function streamConsumerGroup() {
|
||||
|
||||
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);
|
||||
|
||||
@@ -99,6 +103,3 @@ async function streamConsumerGroup() {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
streamConsumerGroup();
|
||||
|
@@ -1,9 +1,9 @@
|
||||
// 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();
|
||||
|
||||
await client.connect();
|
||||
@@ -59,6 +59,3 @@ async function streamConsumer() {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
streamConsumer();
|
||||
|
@@ -1,7 +1,7 @@
|
||||
// A sample stream producer using XADD.
|
||||
// https://redis.io/commands/xadd/
|
||||
import { createClient } from 'redis';
|
||||
|
||||
async function streamProducer() {
|
||||
const client = createClient();
|
||||
|
||||
await client.connect();
|
||||
@@ -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()
|
||||
@@ -41,13 +41,10 @@ async function 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();
|
||||
}
|
||||
|
||||
streamProducer();
|
||||
|
||||
|
@@ -1,10 +1,9 @@
|
||||
// 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();
|
||||
|
||||
await client.connect();
|
||||
@@ -12,7 +11,7 @@ async function timeSeries() {
|
||||
|
||||
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:
|
||||
@@ -121,6 +120,3 @@ async function timeSeries() {
|
||||
}
|
||||
|
||||
await client.quit();
|
||||
}
|
||||
|
||||
timeSeries();
|
||||
|
@@ -1,9 +1,8 @@
|
||||
// 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();
|
||||
|
||||
await client.connect();
|
||||
@@ -12,9 +11,9 @@ async function topK() {
|
||||
await client.del('mytopk');
|
||||
|
||||
// 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 {
|
||||
await client.topK.reserve('mytopk', 10);
|
||||
await client.topK.reserve('mytopk', 10, { width: 400, depth: 10, decay: 0.9 });
|
||||
console.log('Reserved Top K.');
|
||||
} catch (e) {
|
||||
if (e.message.endsWith('key already exists')) {
|
||||
@@ -43,6 +42,7 @@ async function topK() {
|
||||
];
|
||||
|
||||
// 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;
|
||||
@@ -54,6 +54,7 @@ async function topK() {
|
||||
}
|
||||
|
||||
// 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:
|
||||
@@ -67,6 +68,7 @@ async function topK() {
|
||||
console.log(top10);
|
||||
|
||||
// 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);
|
||||
@@ -85,6 +87,7 @@ async function topK() {
|
||||
// ]
|
||||
|
||||
// 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',
|
||||
@@ -97,7 +100,8 @@ async function topK() {
|
||||
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:
|
||||
// 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'
|
||||
@@ -107,6 +111,3 @@ async function topK() {
|
||||
console.log(`Count estimate for lance: ${lanceCount}.`);
|
||||
|
||||
await client.quit();
|
||||
}
|
||||
|
||||
topK();
|
||||
|
Reference in New Issue
Block a user