简体   繁体   English

在 RedisJSON 中操作嵌套的对象数组

[英]Manipulating nested array of obects in RedisJSON

I have a JSON with nested array like below to be saved in Redis.我有一个带有嵌套数组的 JSON,如下所示,要保存在 Redis 中。 I am using RedisJSON module to save the data as JSON.我正在使用 RedisJSON 模块将数据保存为 JSON。

customer:12345 : {
    info : {
        key1: val1,
        key2: val2,
        key3: val3
    },
    rides: [
        {
            rideid: xxx,
            from: fromval,
            to: toval,
            date: dateofride,
            distance: distanceval,
            points: pointsval
        },
        {
            rideid: yyy,
            from: fromval,
            to: toval,
            date: dateofride,
            distance: distanceval,
            points: pointsval
        },
        ...
    ]
}

I have a case where a new item can be added to the array or the existing one can be edited.我有一种情况,可以将新项目添加到数组中,也可以编辑现有项目。 I am using node-redis client with express.js.我正在使用带有 express.js 的 node-redis 客户端。 Express app receives only the data which is changed or added in rides array. Express 应用程序仅接收在游乐设施数组中更改或添加的数据。 If the item is already in the array, new data has to replace the existing array item (rideid is the key of each object), else it has to be added to the array.如果该项已经在数组中,则必须用新数据替换现有的数组项(rideid 是每个对象的键),否则必须将其添加到数组中。 How do I achieve this?我如何实现这一目标?

Given the following JSON给定以下 JSON

{
    "info": {
        "key1": "val1"
    },
    "rides": [{
            "rideid": "xxx",
            "points": 0
        },
        {
            "rideid": "yyy",
            "points": 10
        }
    ]
}

Set on the key customer:12345 in RedisJSON with the following command使用以下命令在 RedisJSON 中设置关键customer:12345

127.0.0.1:6379> JSON.SET customer:12345 . "{\"info\": {\"key1\": \"val1\",\"key2\": \"val2\",\"key3\": \"val3\"},\"rides\":[{\"rideid\": \"xxx\",\"points\": 0 },\t{\"rideid\": \"yyy\",\"points\": 10}]}"

You can update ride with ridded yyy by eg incrementing the score by 5 as follows您可以通过例如将分数增加 5 来更新rided yyy ,如下所示

127.0.0.1:6379> JSON.NUMINCRBY customer:12345 "$.rides[?(@.rideid=='yyy')].points" 5
"[15]"

$.rides[?(@.rideid=='yyy')].points is a JSONPath expression (more here and here and also answered here ) $.rides[?(@.rideid=='yyy')].points是一个 JSONPath 表达式(更多herehere也在这里回答)

To add a new ride添加新行程

127.0.0.1:6379> JSON.ARRAPPEND customer:12345 $.rides "{\"rideid\": \"zzz\",\"points\": 5 }"
1) (integer) 3

All RedisJSON commands can be found here所有 RedisJSON 命令都可以在这里找到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM