*Redis EXISTS 命令 检查 key 是否存在

*EXISTS

*语法

EXISTS key [key ...]

*说明

检查一个或多个 key 是否存在。

从 Redis 3.0.3 开始支持多个 key 参数,返回存在的 key 的数量。

*示例

# 检查单个 key
redis-cli SET key1 "Hello"
redis-cli EXISTS key1

# 检查多个 key
redis-cli SET key2 "World"
redis-cli EXISTS key1 key2 nonexisting

# 返回 0 表示 key 不存在
redis-cli EXISTS nonexisting

# 配合条件操作使用
if [ "$(redis-cli EXISTS mykey)" -eq "1" ]; then
  echo "key exists"
else
  echo "key does not exist"
fi

*返回值

  • 整数(>= 0):存在的 key 的数量

*版本兼容性

版本 说明
>= 1.0.0 可用,仅支持单个 key
>= 3.0.3 支持多个 key

*时间复杂度

O(N),其中 N 是检查的 key 数量。对于单个 key,复杂度为 O(1)。