【问题标题】:Manipulating nested array of obects in RedisJSON在 Redis JSON 中操作嵌套的对象数组
【发布时间】:2022-01-09 11:43:08
【问题描述】:

我有一个带有嵌套数组的 JSON,如下所示,要保存在 Redis 中。我正在使用 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
        },
        ...
    ]
}

我有一种情况,可以将新项目添加到数组中,也可以编辑现有项目。我正在使用带有 express.js 的 node-redis 客户端。 Express 应用程序仅接收在游乐设施数组中更改或添加的数据。如果该项已经在数组中,则必须用新数据替换现有的数组项(rideid 是每个对象的键),否则必须将其添加到数组中。我如何做到这一点?

【问题讨论】:

    标签: json redis node-redis redisjson redislabs


    【解决方案1】:

    给定以下 JSON 文档

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

    使用以下命令在 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}]}"
    

    您可以使用rideid yyy 更新骑行,例如分数加5如下

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

    $.rides[?(@.rideid=='yyy')].points 是一个 JSONPath 表达式(更多 herehere 并且还回答了 here

    添加新行程

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

    所有RedisJSON命令都可以找到here

    【讨论】:

      猜你喜欢
      • 2019-08-11
      • 2020-06-08
      • 1970-01-01
      • 2014-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      相关资源
      最近更新 更多