*Redis LPOS 命令
返回 List 中指定元素第一次或第 N 次出现的位置(索引)。Redis 6.0.6+ 引入。
*语法
LPOS key element [RANK rank] [COUNT num-matches] [MAXLEN len]
*参数说明
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| key | String | 是 | List 键名 |
| element | String | 是 | 要查找的元素 |
| RANK | Integer | 否 | 返回第 rank 次匹配的位置,默认 1(从 1 开始) |
| COUNT | Integer | 否 | 返回最多 num-matches 个匹配位置 |
| MAXLEN | Integer | 否 | 最多搜索 len 个元素 |
*返回值
| 条件 | 返回值 |
|---|---|
| 找到 | 索引位置(Integer)或位置数组(COUNT 时) |
| 未找到 | nil 或空数组 [] |
*时间复杂度
O(N),N 为搜索的元素数量(受 MAXLEN 限制)。
*示例
> RPUSH mylist a b c a d a
(integer) 6
> LPOS mylist a
(integer) 0
# 第 2 次出现
> LPOS mylist a RANK 2
(integer) 3
# 第 3 次出现
> LPOS mylist a RANK 3
(integer) 5
# 返回所有出现位置
> LPOS mylist a COUNT 0
1) (integer) 0
2) (integer) 3
3) (integer) 5
# 限制搜索长度
> LPOS mylist a RANK 2 MAXLEN 4
(nil) # 前 4 个元素中只有 1 个 a
*常见错误
- 对非 List 使用:返回 WRONGTYPE。
*最佳实践
*FAQ
Q: LPOS 返回的索引从 0 开始吗? A: 是。和 Redis 其他 List 命令(LRANGE, LINDEX)一致,从 0 开始。
Q: COUNT=0 是什么意思? A: COUNT=0 返回所有匹配位置。