RedisJSON 技术揭秘(二)用 `JSON.ARRINDEX` 高效查找数组中的值

发布于:2025-07-14 ⋅ 阅读:(19) ⋅ 点赞:(0)

一、指令简介:查找 JSON 数组中的元素位置

语法格式

JSON.ARRINDEX <key> <path> <value> [start [stop]]

参数说明:

  • key:Redis 中存储 JSON 的键;
  • path:JSONPath,指向待搜索的数组;
  • value:你要找的值;
  • start:开始位置(可选,默认 0);
  • stop:结束位置(可选,默认 0,即查完整数组)。

✅ 字符串值应使用双引号包裹再套一层单引号:'"silver"'

返回值说明

  • 成功找到:返回匹配元素的索引位置(从 0 开始);
  • 未找到:返回 -1
  • 匹配路径不是数组:返回 nil
  • 多路径匹配:返回对应路径的数组。

二、实战演练:为产品查找颜色索引

创建 JSON 文档

redis> JSON.SET item:1 $ '{
  "name": "Noise-cancelling Bluetooth headphones",
  "colors": ["black", "silver"]
}'
OK

添加颜色

redis> JSON.ARRAPPEND item:1 $.colors '"blue"'
# 返回数组新长度:3

插入更多颜色(在索引 2 后)

redis> JSON.ARRINSERT item:1 $.colors 2 '"yellow"' '"gold"'
# 结果为:["black", "silver", "yellow", "gold", "blue"]

查找索引位置

redis> JSON.ARRINDEX item:1 $.colors '"silver"'
1) (integer) 1

redis> JSON.ARRINDEX item:1 $.colors '"gold"'
1) (integer) 3

redis> JSON.ARRINDEX item:1 $.colors '"purple"'
1) (integer) -1

三、范围搜索(start/stop)

startstop 支持限制搜索范围,提升性能:

redis> JSON.ARRINDEX item:1 $.colors '"gold"' 0 2
# 不在范围内,返回 -1
1) (integer) -1

redis> JSON.ARRINDEX item:1 $.colors '"gold"' 0 4
1) (integer) 3

注意:stop包含边界,且支持负数索引(如 Python 切片)。

四、与多路径 JSON 搭配

如果你有嵌套数组,如:

{
  "variants": [
    {"colors": ["white", "red"]},
    {"colors": ["black", "silver", "gold"]}
  ]
}

使用 .. 深度匹配:

redis> JSON.ARRINDEX item:2 $..colors '"gold"'
1) (integer) -1
2) (integer) 2

第一组找不到,返回 -1;第二组返回 2

五、Python 示例(redis-py ≥ 5.0)

from redis import Redis
from redis.commands.json.path import Path

r = Redis(decode_responses=True)
r.json().set("item:1", Path.root_path(), {
    "colors": ["black", "silver", "yellow", "gold", "blue"]
})
index = r.execute_command("JSON.ARRINDEX", "item:1", "$.colors", '"gold"')
print(index)  # [3]

六、性能 & 实战建议

场景 建议
高频查找 搭配缓存 key → index
长数组搜索 加上 start/stop 限定范围
多路径搜索 $..colors + 并发 client
元素不存在时追加 搭配 ARRINDEX + ARRAPPEND 使用

七、常见问题排查

问题 解决方法
返回 nil 确认路径对应的值为 JSON 数组
索引总是 -1 字符串是否正确加引号?应为 '"text"'
多路径结果混乱 每个路径的结果独立返回,注意顺序
范围无效 stop 是“包含”索引,负数从末尾算起

八、总结

JSON.ARRINDEX 是 RedisJSON 操作数组中查找的利器。相比传统 JSON 处理方式,它在性能、可控性与可读性上都大幅领先。如果你在构建一个文档系统、推荐系统或商品目录,合理利用此指令可以极大提升数据处理效率。


网站公告

今日签到

点亮在社区的每一天
去签到