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

Adds RedisJSON example.

This commit is contained in:
Simon Prickett
2021-11-24 19:32:37 +00:00
parent 967ee5801c
commit 055af50890
2 changed files with 82 additions and 0 deletions

View File

@@ -8,6 +8,7 @@ This folder contains example scripts showing how to use Node Redis in different
| `command-with-modifiers.js` | Define a script that allows to run a command with several modifiers |
| `connect-as-acl-user.js` | Connect to Redis 6 using an ACL user |
| `lua-multi-incr.js` | Define a custom lua script that allows you to perform INCRBY on multiple keys |
| `managing-json.js` | Store, retrieve and manipulate JSON data atomically with [RedisJSON](https://redisjson.io/) |
| `search-hashes.js` | Uses [RediSearch](https://redisearch.io) to index and search data in hashes |
| `search+json.js` | Uses [RediSearch](https://redisearch.io/) and [RedisJSON](https://redisjson.io/) to index and search JSON data |
| `set-scan.js` | An example script that shows how to use the SSCAN iterator functionality |

81
examples/managing-json.js Normal file
View File

@@ -0,0 +1,81 @@
// Store, retrieve and manipulate JSON data atomically with RedisJSON.
import { createClient } from 'redis';
async function managingJSON() {
const client = createClient();
await client.connect();
await client.del('noderedis:jsondata');
// Store a JSON object...
await client.json.set('noderedis:jsondata', '$', {
name: 'Roberta McDonald',
pets: [
{
name: 'Fluffy',
species: 'dog',
age: 5,
isMammal: true
},
{
name: 'Rex',
species: 'dog',
age: 3,
isMammal: true
},
{
name: 'Goldie',
species: 'fish',
age: 2,
isMammal: false
}
],
address: {
number: 99,
street: 'Main Street',
city: 'Springfield',
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', {
path: [
'.pets[1].name',
'.pets[1].age'
]
});
// { '.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 is 3 years old now.
console.log(`Goldie is ${JSON.stringify(results)} years old now.`);
// Add a new pet...
await client.json.arrAppend('noderedis:jsondata', '.pets', {
name: '',
species: 'bird',
isMammal: false,
age: 1
});
// 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();