英文:
Redis: get element from JSON array by index
问题
我使用的包是redis。我使用以下命令将JSON数组存储在Redis中:
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');
我做错了什么?
英文:
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?
答案1
得分: 1
以下是您要翻译的内容:
尝试:
```js
await redisClient.json.get('car.volume.tire', { path: ['[0]'] });
或者你可以像Guy Royse建议的那样将path
作为一个字符串传递:
await redisClient.json.get('car.volume.tire', { path: '[0]' });
完整示例
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服务器错误", 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();
<details>
<summary>英文:</summary>
Try:
```js
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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论