skip to Main Content

I tried to use the "@redis/json" library to set json object in Redis.

    const redisClient = await createClient({
                url: `redis://${redis.host}:${redis.port}`,                
            });
            await redisClient.connect();
            redisClient.json.set()  //getting json undefined  error

But redisClient doesn’t recognize the json object.
The docs are not clear

2

Answers


  1. Chosen as BEST ANSWER

    @Simon answer is correct when installing the entire 'redis' library. This answer works when importing only the @redis/client + @redis/json

    import { createClient } from '@redis/client';
    import RedisJsonModule from '@redis/json';
    
    const redisClient = createClient({
                url: `redis://${redisConfig.host}:${redisConfig.port}`,
                socket: { tls: true },
                modules: { json: RedisJsonModule },
            });
    await redisClient.connect();
    

    if you are using typescript the redisClient type is RedisClientType<{ json: typeof RedisJsonModule }, RedisFunctions, RedisScripts>


  2. The documentation definitely needs work, and that’s something we’re putting time into. There are several example scripts here that we try to keep up to date with all the new functionality:

    https://github.com/redis/node-redis/tree/master/examples

    Here’s an example of how to use the JSON commands:

    https://github.com/redis/node-redis/blob/master/examples/managing-json.js

    Your code looks OK to me, you shouldn’t need to await the createClient call though.

    Here’s a basic working example:

    output:

    $ node index.js
    {
      hello: 'world',
      nums: [ 0, 1, 2, 3 ],
      obj: { hello: 'there', age: 99 }
    }
    

    package.json:

    {
      "name": "nrjson",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "type": "module",
      "scripts": {
        "test": "echo "Error: no test specified" && exit 1"
      },
      "author": "Simon Prickett",
      "license": "MIT",
      "dependencies": {
        "redis": "^4.6.7"
      }
    }
    

    index.js:

    import { createClient } from 'redis';
    
    const client = createClient();
    
    await client.connect();
    await client.del('noderedis:jsondata');
    
    // Store a JSON object...
    await client.json.set('noderedis:jsondata', '$', {
      hello: "world",
      nums: [ 0, 1, 2, 3],
      obj: {
        "hello": "there",
        "age": 99
      }
    });
    
    // And retrieve it....
    console.log(await client.json.get('noderedis:jsondata', '$'));
    
    await client.quit();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search