skip to Main Content

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


  1. 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 the element variable in the pseudocode).

    I remember working with lua about 9 years ago, so this doesn’t really look like lua either to me.

    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.

    Login or Signup to reply.
  2. As @Dinei said, the example given is pseudocode.

    Let’s look at it (I added line numbers for us to refer to):

    1 WATCH zset
    2 element = ZRANGE zset 0 0
    3 MULTI
    4 ZREM zset element
    5 EXEC
    

    The point of the exercise is to solve the race condition that would occur if we only read the key (with ZRANGE, in line 2), and then modify the key (with ZREM 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-variable element.

    Then, in line 4, we are using that value in our “set” operation, and of course lines 1, 3 and 5 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 the ZREM 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 from zrange and then passed that value to the zrem command:

    127.0.0.1:6379> zadd zset 1 a
    (integer) 1
    127.0.0.1:6379> watch zset
    OK
    127.0.0.1:6379> zrange zset 0 0
    1) "a"
    127.0.0.1:6379> multi
    OK
    127.0.0.1:6379> zrem zset a
    QUEUED
    127.0.0.1:6379> exec
    1) (integer) 1
    127.0.0.1:6379>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search