我使用的软件包是redis。我使用以下命令在 Redis 中存储 JSON 数组:
await redisClient.json.set('car.volume.tire', '$', []);
await redisClient.json.arrAppend('car.volume.tire', '$', { hello: 'there' });
但是当我想通过索引检索元素时,我收到 null
:
await redisClient.json.get(`car.volume.tire[0]`);
但是,以下命令返回完整的 JSON 数组:
await redisClient.json.get(`car.volume.tire`);
我做错了什么?
最佳答案
尝试:
await redisClient.json.get('car.volume.tire', { path: ['[0]'] });
或者您可以按照 Guy Royse 的建议将 path
作为字符串传递:
await redisClient.json.get('car.volume.tire', { path: '[0]' });
参见:"Retrieving JSON Documents from Redis"
完整示例
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();
关于javascript - Redis:通过索引从JSON数组中获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76476302/