|
| 1 | +// Store, retrieve and manipulate JSON data atomically with RedisJSON. |
| 2 | + |
| 3 | +import { createClient } from 'redis'; |
| 4 | + |
| 5 | +async function managingJSON() { |
| 6 | + const client = createClient(); |
| 7 | + |
| 8 | + await client.connect(); |
| 9 | + await client.del('noderedis:jsondata'); |
| 10 | + |
| 11 | + // Store a JSON object... |
| 12 | + await client.json.set('noderedis:jsondata', '$', { |
| 13 | + name: 'Roberta McDonald', |
| 14 | + pets: [ |
| 15 | + { |
| 16 | + name: 'Fluffy', |
| 17 | + species: 'dog', |
| 18 | + age: 5, |
| 19 | + isMammal: true |
| 20 | + }, |
| 21 | + { |
| 22 | + name: 'Rex', |
| 23 | + species: 'dog', |
| 24 | + age: 3, |
| 25 | + isMammal: true |
| 26 | + }, |
| 27 | + { |
| 28 | + name: 'Goldie', |
| 29 | + species: 'fish', |
| 30 | + age: 2, |
| 31 | + isMammal: false |
| 32 | + } |
| 33 | + ], |
| 34 | + address: { |
| 35 | + number: 99, |
| 36 | + street: 'Main Street', |
| 37 | + city: 'Springfield', |
| 38 | + state: 'OH', |
| 39 | + country: 'USA' |
| 40 | + } |
| 41 | + }); |
| 42 | + |
| 43 | + // Retrieve the name and age of the second pet in the pets array. |
| 44 | + let results = await client.json.get('noderedis:jsondata', { |
| 45 | + path: [ |
| 46 | + '.pets[1].name', |
| 47 | + '.pets[1].age' |
| 48 | + ] |
| 49 | + }); |
| 50 | + |
| 51 | + // { '.pets[1].name': 'Rex', '.pets[1].age': 3 } |
| 52 | + console.log(results); |
| 53 | + |
| 54 | + // Goldie had a birthday, increment the age... |
| 55 | + await client.json.numIncrBy('noderedis:jsondata', '.pets[2].age', 1); |
| 56 | + results = await client.json.get('noderedis:jsondata', { |
| 57 | + path: '.pets[2].age' |
| 58 | + }); |
| 59 | + |
| 60 | + // Goldie is 3 years old now. |
| 61 | + console.log(`Goldie is ${JSON.stringify(results)} years old now.`); |
| 62 | + |
| 63 | + // Add a new pet... |
| 64 | + await client.json.arrAppend('noderedis:jsondata', '.pets', { |
| 65 | + name: '', |
| 66 | + species: 'bird', |
| 67 | + isMammal: false, |
| 68 | + age: 1 |
| 69 | + }); |
| 70 | + |
| 71 | + // How many pets do we have now? |
| 72 | + const numPets = await client.json.arrLen('noderedis:jsondata', '.pets'); |
| 73 | + |
| 74 | + // We now have 4 pets. |
| 75 | + console.log(`We now have ${numPets} pets.`); |
| 76 | + |
| 77 | + await client.quit(); |
| 78 | +} |
| 79 | + |
| 80 | +managingJSON(); |
| 81 | + |
0 commit comments