I am trying to run the code from the redis transactions page. Specifically, this part:
WATCH zset
element = ZRANGE zset 0 0
MULTI
ZREM zset element
EXEC
If I try to do it from the cli, line by line, I get this:
localhost:6380> zadd set 1 a
(integer) 1
localhost:6380> WATCH zset
localhost:6380> element = ZRANGE zset 0 0
(error) ERR unknown command 'element'
OK
which probably means I’m doing something wrong? I remember working with lua about 9 years ago, so this doesn’t really look like lua either to me.
How does someone run that snippet? Is it only some kind of pseudocode?
2
Answers
Yes, it is some kind of pseudocode.
redis-cli
only accepts Redis commands, it is not a full-fledged editor nor supports direct Lua scripting (neither variables like theelement
variable in the pseudocode).This is not Lua, it is pseudocode. Actually, the Redis Transactions page you linked to does not refer to Lua at all (and that’s why @Piglet’s comment in your post makes sense).
However, it is possible to execute Lua scripts by using Redis’
EVAL
command.As @Dinei said, the example given is pseudocode.
Let’s look at it (I added line numbers for us to refer to):
The point of the exercise is to solve the race condition that would occur if we only read the key (with
ZRANGE
, in line2
), and then modify the key (withZREM
in line 4). I assume you understand the problem if we didn’t use the “CAS” semantics, so no need to get into it.As pointed out,
redis-cli
just gives you the ability to run redis commands and see their replies, but not save values in variables, etc.So the idea of the example is that in line
2
, we are “saving” the result of the “read” operation, into a pseudo-variableelement
.Then, in line
4
, we are using that value in our “set” operation, and of course lines1
,3
and5
are just the “CAS” commands to ensure there is no race condition.Presumably the actual usage of such commands would be done from a redis client in a programming language that would allow us to save the return value of the
ZRANGE
and then use it later in theZREM
command.But if you wanted to run it in
redis-cli
, you’d see this, where we pretend that our client-side code would have read and saved"a"
that was returned fromzrange
and then passed that value to thezrem
command: