redis.exceptions.ResponseError: 运行脚本时出错(调用 f_abcdef123456):@user_script:1: WRONGTYPE 操作针对持有错误类型值的键
redis.exceptions.ResponseError: Error running script (call to f_abcdef123456): @user_script:1: WRONGTYPE Operation against a key holding the wrong kind of value
ID: database/redis-lua-script-execution-error
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Redis 7.2.4 | active | — | — | — |
| Redis 6.2.14 | active | — | — | — |
| Redis Stack 7.2.0 | active | — | — | — |
根因分析
Redis Lua 脚本尝试对键执行与存储的数据类型不兼容的操作(例如对字符串键执行 LPUSH),导致 WRONGTYPE 错误。
English
A Redis Lua script attempted to perform an operation (e.g., LPUSH on a string key) that is incompatible with the data type stored at the key, causing a WRONGTYPE error.
官方文档
https://redis.io/docs/latest/develop/interact/programmability/error-handling/解决方案
-
Identify the offending key by running: TYPE <key> in redis-cli. Then either delete the key (DEL <key>) or modify the script to handle the existing type (e.g., use EXISTS to check type before operations).
-
Update the Lua script to use TYPE command to check the key's type before performing operations, and return an error or handle gracefully: local keyType = redis.call('TYPE', KEYS[1]); if keyType ~= 'list' then return redis.error_reply('Expected list, got ' .. keyType) end -
If the key should be a list but is currently a string, convert it by deleting and recreating: DEL mykey; LPUSH mykey value1 value2; then retry the script.
无效尝试
常见但无效的做法:
-
Flushing all keys with FLUSHALL to clear the data type mismatch
95% 失败
This deletes all data, which is an extreme measure; the script will still fail if the same key is recreated with the wrong type.
-
Ignoring the error and retrying the script
100% 失败
The error is deterministic; retrying without fixing the key type will produce the same error every time.
-
Using EVAL instead of EVALSHA to force script recompilation
90% 失败
The error is not due to script caching; it's a runtime type mismatch. EVAL will still fail with the same error.