Skip to content

chore(examples): fix examples for v5 #2938

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ We'd love to see more examples here. If you have an idea that you'd like to see

To set up the examples folder so that you can run an example / develop one of your own:

```
$ git clone https://github.com/redis/node-redis.git
$ cd node-redis
$ npm install -ws && npm run build-all
$ cd examples
$ npm install
```bash
git clone https://github.com/redis/node-redis.git
cd node-redis
npm install -ws && npm run build
cd examples
npm install
```

### Coding Guidelines for Examples
Expand Down Expand Up @@ -91,5 +91,5 @@ await client.connect();

// Add your example code here...

client.destroy();
client.close();
```
5 changes: 2 additions & 3 deletions examples/blocking-list-pop.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@
// The script will be blocked until the LPUSH command is executed.
// After which we log the list and quit the client.

import { createClient, commandOptions } from 'redis';
import { createClientPool } from 'redis';

const client = createClient();
const client = createClientPool();

await client.connect();

const keyName = 'keyName';

const blpopPromise = client.blPop(
commandOptions({ isolated: true }),
keyName,
0
);
Expand Down
2 changes: 1 addition & 1 deletion examples/command-with-modifiers.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Define a custom script that shows example of SET command
// with several modifiers.

import { createClient } from '../packages/client';
import { createClient } from 'redis';

const client = createClient();

Expand Down
5 changes: 2 additions & 3 deletions examples/connect-to-cluster.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// This is an example script to connect to a running cluster.
// After connecting to the cluster the code sets and get a value.

// To setup this cluster you can follow the guide here:
// To setup this cluster you can follow the guide here:
// https://redis.io/docs/manual/scaling/
// In this guide the ports which are being used are 7000 - 7005

Expand Down Expand Up @@ -29,5 +29,4 @@ await cluster.connect();
await cluster.set('hello', 'cluster');
const value = await cluster.get('hello');
console.log(value);

await cluster.quit();
await cluster.close();
6 changes: 6 additions & 0 deletions examples/dump-and-restore.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ const client = await createClient({
console.log('Redis Client Error', err);
}).connect();

// Make sure the source key exists
await client.set('source', 'value');

// Make sure destination doesnt exist
await client.del('destination');

// DUMP a specific key into a local variable
const dump = await client.dump('source');

Expand Down
10 changes: 8 additions & 2 deletions examples/get-server-time.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@ const client = createClient();
await client.connect();

const serverTime = await client.time();
// 2022-02-25T12:57:40.000Z { microseconds: 351346 }
// In v5, TIME returns [unixTimestamp: string, microseconds: string] instead of Date
// Example: ['1708956789', '123456']
console.log(serverTime);

client.destroy();
// Convert to JavaScript Date if needed
const [seconds, microseconds] = serverTime;
const date = new Date(parseInt(seconds) * 1000 + parseInt(microseconds) / 1000);
console.log('Converted to Date:', date);

client.close();
4 changes: 2 additions & 2 deletions examples/hyperloglog.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const client = createClient();
await client.connect();

// Use `pfAdd` to add an element to a Hyperloglog, creating the Hyperloglog if necessary.
// await client.pfAdd(key, value)
// await client.pfAdd(key, value) // returns 1 or 0

// To get a count, the `pfCount` method is used.
// await client.pfCount(key)
Expand Down Expand Up @@ -48,4 +48,4 @@ try {
console.error(e);
}

client.destroy();
client.close();
8 changes: 5 additions & 3 deletions examples/lua-multi-incr.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ const client = createClient({
'redis.pcall("INCRBY", KEYS[1], ARGV[1]),' +
'redis.pcall("INCRBY", KEYS[2], ARGV[1])' +
'}',
transformArguments(key1, key2, increment) {
return [key1, key2, increment.toString()];
},
parseCommand(parser, key1, key2, increment) {
parser.pushKey(key1);
parser.pushKey(key2);
parser.push(increment.toString());
},
}),
},
});
Expand Down
11 changes: 8 additions & 3 deletions examples/managing-json.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ results = await client.json.get('noderedis:jsondata', {
});

// Goldie is 3 years old now.
console.log(`Goldie is ${JSON.stringify(results[0])} years old now.`);
console.log(`Goldie is ${JSON.parse(results)[0]} years old now.`);

// Add a new pet...
await client.json.arrAppend('noderedis:jsondata', '$.pets', {
Expand All @@ -68,9 +68,14 @@ await client.json.arrAppend('noderedis:jsondata', '$.pets', {
});

// How many pets do we have now?
const numPets = await client.json.arrLen('noderedis:jsondata', '$.pets');
const numPets = await client.json.arrLen('noderedis:jsondata', { path: '$.pets' });

// We now have 4 pets.
console.log(`We now have ${numPets} pets.`);

client.destroy();
const rex = { name: 'Rex', species: 'dog', age: 3, isMammal: true }

const index = await client.json.arrIndex( 'noderedis:jsondata', '$.pets', rex);
console.log(`Rex is at index ${index}`);

client.close();
4 changes: 2 additions & 2 deletions examples/package.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
{
"name": "node-redis-examples",
"version": "1.0.0",
"description": "node-redis 4 example script",
"description": "node-redis 5 example script",
"main": "index.js",
"private": true,
"type": "module",
"dependencies": {
"redis": "../packages/client"
"redis": "../packages/redis"
}
}

8 changes: 4 additions & 4 deletions examples/search-hashes.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// This example demonstrates how to use RediSearch to index and query data
// stored in Redis hashes.

import { createClient, SchemaFieldTypes } from 'redis';
import { createClient, SCHEMA_FIELD_TYPE } from 'redis';

const client = createClient();

Expand All @@ -12,11 +12,11 @@ try {
// Documentation: https://redis.io/commands/ft.create/
await client.ft.create('idx:animals', {
name: {
type: SchemaFieldTypes.TEXT,
type: SCHEMA_FIELD_TYPE.TEXT,
SORTABLE: true
},
species: SchemaFieldTypes.TAG,
age: SchemaFieldTypes.NUMERIC
species: SCHEMA_FIELD_TYPE.TAG,
age: SCHEMA_FIELD_TYPE.NUMERIC
}, {
ON: 'HASH',
PREFIX: 'noderedis:animals'
Expand Down
16 changes: 8 additions & 8 deletions examples/search-json.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// https://redis.io/docs/stack/search/
// https://redis.io/docs/stack/json/

import { createClient, SchemaFieldTypes, AggregateGroupByReducers, AggregateSteps } from 'redis';
import { createClient, SCHEMA_FIELD_TYPE, FT_AGGREGATE_GROUP_BY_REDUCERS, FT_AGGREGATE_STEPS } from 'redis';

const client = createClient();

Expand All @@ -14,19 +14,19 @@ await client.connect();
try {
await client.ft.create('idx:users', {
'$.name': {
type: SchemaFieldTypes.TEXT,
type: SCHEMA_FIELD_TYPE.TEXT,
SORTABLE: true
},
'$.age': {
type: SchemaFieldTypes.NUMERIC,
type: SCHEMA_FIELD_TYPE.NUMERIC,
AS: 'age'
},
'$.coins': {
type: SchemaFieldTypes.NUMERIC,
type: SCHEMA_FIELD_TYPE.NUMERIC,
AS: 'coins'
},
'$.email': {
type: SchemaFieldTypes.TAG,
type: SCHEMA_FIELD_TYPE.TAG,
AS: 'email'
}
}, {
Expand Down Expand Up @@ -119,13 +119,13 @@ console.log(
JSON.stringify(
await client.ft.aggregate('idx:users', '*', {
STEPS: [{
type: AggregateSteps.GROUPBY,
type: FT_AGGREGATE_STEPS.GROUPBY,
REDUCE: [{
type: AggregateGroupByReducers.AVG,
type: FT_AGGREGATE_GROUP_BY_REDUCERS.AVG,
property: 'age',
AS: 'averageAge'
}, {
type: AggregateGroupByReducers.SUM,
type: FT_AGGREGATE_GROUP_BY_REDUCERS.SUM,
property: 'coins',
AS: 'totalCoins'
}]
Expand Down
6 changes: 3 additions & 3 deletions examples/search-knn.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// Inspired by RediSearch Python tests:
// https://github.com/RediSearch/RediSearch/blob/06e36d48946ea08bd0d8b76394a4e82eeb919d78/tests/pytests/test_vecsim.py#L96

import { createClient, SchemaFieldTypes, VectorAlgorithms } from 'redis';
import { createClient, SCHEMA_FIELD_TYPE, SCHEMA_VECTOR_FIELD_ALGORITHM } from 'redis';

const client = createClient();

Expand All @@ -15,8 +15,8 @@ try {
// Documentation: https://redis.io/docs/stack/search/reference/vectors/
await client.ft.create('idx:knn-example', {
v: {
type: SchemaFieldTypes.VECTOR,
ALGORITHM: VectorAlgorithms.HNSW,
type: SCHEMA_FIELD_TYPE.VECTOR,
ALGORITHM: SCHEMA_VECTOR_FIELD_ALGORITHM.HNSW,
TYPE: 'FLOAT32',
DIM: 2,
DISTANCE_METRIC: 'COSINE'
Expand Down
12 changes: 9 additions & 3 deletions examples/set-scan.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,14 @@ const client = createClient();
await client.connect();

const setName = 'setName';
for await (const member of client.sScanIterator(setName)) {
console.log(member);

for await (const members of client.sScanIterator(setName)) {
console.log('Batch of members:', members);

// Process each member in the batch if needed
for (const member of members) {
console.log('Individual member:', member);
}
}

client.destroy();
client.close();
28 changes: 25 additions & 3 deletions examples/sorted-set.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,30 @@ await client.zAdd('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);
for await (const membersWithScores of client.zScanIterator('mysortedset')) {
console.log('Batch of members with scores:', membersWithScores);

for (const memberWithScore of membersWithScores) {
console.log('Individual member with score:', memberWithScore);
}
}

client.destroy();
await client.zAdd('anothersortedset', [
{
score: 99,
value: 'Ninety Nine'
},
{
score: 102,
value: 'One Hundred and Two'
}
]);

// Intersection of two sorted sets
const intersection = await client.zInter([
{ key: 'mysortedset', weight: 1 },
{ key: 'anothersortedset', weight: 1 }
]);
console.log('Intersection:', intersection);

client.close();
16 changes: 8 additions & 8 deletions examples/stream-consumer-group.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
//
// $ node stream-consumer-group.js consumer2

import { createClient, commandOptions } from 'redis';
import { createClient } from 'redis';

const client = createClient();

Expand All @@ -46,14 +46,13 @@ try {

console.log(`Starting consumer ${consumerName}.`);

const pool = client.createPool();

while (true) {
try {
// https://redis.io/commands/xreadgroup/
let response = await client.xReadGroup(
commandOptions({
isolated: true
}),
'myconsumergroup',
let response = await pool.xReadGroup(
'myconsumergroup',
consumerName, [
// XREADGROUP can read from multiple streams, starting at a
// different ID for each...
Expand Down Expand Up @@ -91,9 +90,10 @@ while (true) {
// stream entry.
// https://redis.io/commands/xack/
const entryId = response[0].messages[0].id;
await client.xAck('mystream', 'myconsumergroup', entryId);
const ackResult = await pool.xAck('mystream', 'myconsumergroup', entryId);

console.log(`Acknowledged processing of entry ${entryId}.`);
// ackResult will be 1 if the message was successfully acknowledged, 0 otherwise
console.log(`Acknowledged processing of entry ${entryId}. Result: ${ackResult}`);
} else {
// Response is null, we have read everything that is
// in the stream right now...
Expand Down
10 changes: 5 additions & 5 deletions examples/time-series.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Requires the RedisTimeSeries module: https://redis.io/docs/stack/timeseries/

import { createClient } from 'redis';
import { TimeSeriesDuplicatePolicies, TimeSeriesEncoding, TimeSeriesAggregationType } from '@redis/time-series';
import { TIME_SERIES_DUPLICATE_POLICIES, TIME_SERIES_ENCODING, TIME_SERIES_AGGREGATION_TYPE } from '@redis/time-series';

const client = createClient();

Expand All @@ -14,8 +14,8 @@ try {
// https://redis.io/commands/ts.create/
const created = await client.ts.create('mytimeseries', {
RETENTION: 86400000, // 1 day in milliseconds
ENCODING: TimeSeriesEncoding.UNCOMPRESSED, // No compression
DUPLICATE_POLICY: TimeSeriesDuplicatePolicies.BLOCK // No duplicates
ENCODING: TIME_SERIES_ENCODING.UNCOMPRESSED, // No compression
DUPLICATE_POLICY: TIME_SERIES_DUPLICATE_POLICIES.BLOCK // No duplicates
});

if (created === 'OK') {
Expand Down Expand Up @@ -74,7 +74,7 @@ try {
const rangeResponse = await client.ts.range('mytimeseries', fromTimestamp, toTimestamp, {
// Group into 10 second averages.
AGGREGATION: {
type: TimeSeriesAggregationType.AVERAGE,
type: TIME_SERIES_AGGREGATION_TYPE.AVG,
timeBucket: 10000
}
});
Expand Down Expand Up @@ -119,4 +119,4 @@ try {
console.error(e);
}

client.destroy();
client.close();
Loading
Loading