1

The package I'm using is redis. I used the following command to store a JSON array in Redis:

await redisClient.json.set('car.volume.tire', '$', []);
await redisClient.json.arrAppend('car.volume.tire', '$', { hello: 'there' });

But when I want to retrieve the element by index, I receive null:

await redisClient.json.get(`car.volume.tire[0]`);

However, the following returns the full JSON array:

await redisClient.json.get(`car.volume.tire`);

What am I doing wrong?

user8555937
  • 2,161
  • 1
  • 14
  • 39
  • 1
    Have you tried: `await redisClient.json.get('car.volume.tire', { path: ['[0]'] });`? See: [_"Retrieving JSON Documents from Redis"_](https://github.com/redis/node-redis/tree/master/packages/json#retrieving-json-documents-from-redis) – Mr. Polywhirl Jun 14 '23 at 17:57
  • @Mr.Polywhirl it works! Thank you – user8555937 Jun 14 '23 at 18:34

1 Answers1

1

Try:

await redisClient.json.get('car.volume.tire', { path: ['[0]'] });

or you can pass path as just a string as Guy Royse suggested:

await redisClient.json.get('car.volume.tire', { path: '[0]' });

See: "Retrieving JSON Documents from Redis"


Full example

import dotenv from "dotenv";
import { createClient } from "redis";

dotenv.config();

const { REDIS_HOST, REDIS_PORT } = process.env;

const redisClient = createClient({
  socket: {
    host: REDIS_HOST,
    port: REDIS_PORT,
  },
});

redisClient.on("error", (err) => console.log("Redis Server Error", err));

await redisClient.connect();

await redisClient.json.set("car.volume.tire", "$", []);
await redisClient.json.arrAppend("car.volume.tire", "$", { hello: "there" });

const found = await redisClient.json.get("car.volume.tire", { path: "[0]" });

console.log(found); // { hello: 'there' }

redisClient.disconnect();
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • 1
    You can also provide a single path as just a string like this: `await redisClient.json.get('car.volume.tire', { path: '[0]' });` – Guy Royse Jun 14 '23 at 19:56
  • 1
    @GuyRoyse Hey, I just found your [`redis-stack-server` answer](https://stackoverflow.com/a/74630354/1762224) to get the JSON module working on Mac, Thanks. – Mr. Polywhirl Jun 14 '23 at 23:47
  • Happy to be a small part of the solution! – Guy Royse Jun 15 '23 at 16:08