JSON.ARRINSERT

语法
JSON.ARRINSERT key path index value [value ...]
可用版本
Redis 开源版 / JSON 1.0.0
时间复杂度
当 path 解析为单个值时,时间复杂度为 O(N),其中 N 是数组的大小;当 path 解析为多个值时,时间复杂度为 O(N),其中 N 是键的大小。
ACL 类别
@json, @write, @slow,

json 值插入到 path 指定数组的 index 位置之前(向右移动元素)

示例

必需参数

key

要修改的键。

value

是要在一个或多个数组中插入的一个或多个值。

关于在 JSON 命令中使用字符串
要将字符串指定为要插入的数组值,请将带引号的字符串用额外的单引号括起来。示例:'"silver"'。有关更详细的用法,请参阅示例
index

是要插入值在数组中的位置。该 index 必须在数组的范围内。在 index 0 插入会将值前置到数组开头。负值 index 从数组末尾开始计算。

可选参数

path

要指定的 JSONPath。默认为根路径 $

返回值

JSON.ARRINSERT 返回一个数组,其中包含每个 path 的整数回复(数组的新大小),如果匹配的 JSON 值不是数组,则返回 nil。有关回复的更多信息,请参阅Redis 序列化协议规范

示例

在产品颜色列表中指定位置添加新颜色

创建一个关于黑色和银色降噪耳机的文档。

redis> JSON.SET item:1 $ '{"name":"Noise-cancelling Bluetooth headphones","description":"Wireless Bluetooth headphones with noise-cancelling technology","connection":{"wireless":true,"type":"Bluetooth"},"price":99.98,"stock":25,"colors":["black","silver"]}'
OK

将颜色 blue 添加到 colors 数组末尾。JSON.ARRAPEND 返回数组的新大小。

redis> JSON.ARRAPPEND item:1 $.colors '"blue"'
1) (integer) 3

返回 colors 数组的新长度。

redis> JSON.GET item:1
"{\"name\":\"Noise-cancelling Bluetooth headphones\",\"description\":\"Wireless Bluetooth headphones with noise-cancelling technology\",\"connection\":{\"wireless\":true,\"type\":\"Bluetooth\"},\"price\":99.98,\"stock\":25,\"colors\":[\"black\",\"silver\",\"blue\"]}"

获取产品的颜色列表。

redis> JSON.GET item:1 '$.colors[*]'
"[\"black\",\"silver\",\"blue\"]"

在第二个颜色后面插入另外两种颜色。现在你有五种颜色。

redis> JSON.ARRINSERT item:1 $.colors 2 '"yellow"' '"gold"'
1) (integer) 5

获取更新后的颜色列表。

redis> JSON.GET item:1 $.colors
"[[\"black\",\"silver\",\"yellow\",\"gold\",\"blue\"]]"

另请参阅

JSON.ARRAPPEND | JSON.ARRINDEX


评价此页面
返回顶部 ↑