NOTE

2.7 Redis Commands

1. Redis general commands - keys pattern queries matching keys - Redis supports fuzzy key matching with three wildcards: *, ?, [] - * matches any number of characters - ? matches one character - [] matches one character inside the brackets - redis-cli can only query data on the current node - SCAN cursor

Redis / CacheCreated Updated 6 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Redis General Commands

  • keys pattern: query matching keys.
    • Redis supports fuzzy key matching with three wildcards: *, ?, [].
      • *: matches any number of characters.
      • ?: matches a single character.
      • []: matches one character inside the brackets.
    • redis-cli can only query data on the current node.
redis 127.0.0.1:6379> flushdb
OK
redis 127.0.0.1:6379> keys *
(empty list or set)
redis 127.0.0.1:6379> mset one 1 two 2 three 3 four 4
OK
redis 127.0.0.1:6379> keys o*
1) "one"
redis 127.0.0.1:6379> key *o
(error) ERR unknown command 'key'
redis 127.0.0.1:6379> keys *o
1) "two"
redis 127.0.0.1:6379> keys ???
1) "one"
2) "two"
redis 127.0.0.1:6379> keys on?
1) "one"
redis 127.0.0.1:6379> set ons yes
OK
redis 127.0.0.1:6379> keys on[eaw]
1) "one"
  • SCAN cursor [MATCH pattern] [COUNT count] [TYPE type]
    • Paginated query.
    • redis-cli can only query data on the current node.
127.0.0.1:6379> set a b
-> Redirected to slot [15495] located at 127.0.0.1:6381
OK
127.0.0.1:6381> set b c
-> Redirected to slot [3300] located at 127.0.0.1:6379
OK
127.0.0.1:6379> set d e
-> Redirected to slot [11298] located at 127.0.0.1:6381
OK
127.0.0.1:6381> SCAN 0 match * count 1
1) "1"
2) 1) "a"
127.0.0.1:6381> SCAN 1 match * count 1
1) "3"
2) 1) "d"
127.0.0.1:6381> SCAN 3 match * count 1
1) "0"
2) (empty list or set)
127.0.0.1:6381> keys *
1) "d"
2) "a"
127.0.0.1:6381>
  • randomkey: returns a random key.

  • exists key

    • Checks whether the key exists; returns 1/0.
  • type key

    • Returns the type of the value stored at the key.
    • Types include string, list, set, sorted set, and hash.
  • ttl key

    • Purpose: query the lifetime of a key.
    • Returns: seconds.
    • Note: historically, a non-existent key, an expired key, or a key without expiry returned -1.
    • Since Redis 2.8, a non-existent key returns -2.
  • expire key integer-value

    • Purpose: set the key lifetime in seconds.
    • Similarly:
      • pexpire key milliseconds: set the lifetime in milliseconds.
      • pttl key: return the lifetime in milliseconds.
  • persist key

    • Purpose: make the specified key permanently valid.

2. Redis Data-Structure Commands

2.1. string

  • get, set, del

  • incr, decr, incrby, decrby

  • set, setnx

  • mget, mset

  • getset, append, strlen

  • incrbyfloat, getrange, setrange

  • set key value [ex seconds] / [px milliseconds] [nx] / [xx]

For example: set a 1 ex 10, valid for 10 seconds.
set a 1 px 9000, valid for 9 seconds.

Note: EX and PX are mutually exclusive expiration options and cannot be used together.

nx: execute only when the key does not exist.
xx: execute only when the key exists.

  • mset: multi-set; set multiple key-value pairs at once.
    Example: mset key1 v1 key2 v2 ....

  • get key
    Purpose: get the value of a key.

  • mget key1 key2 ..keyn
    Purpose: get the values of multiple keys.

  • setrange key offset value
    Purpose: overwrite bytes in the string starting at offset with value.

redis 127.0.0.1:6379> set greet hello
OK
redis 127.0.0.1:6379> setrange greet 2 x
(integer) 5
redis 127.0.0.1:6379> get greet
"hexlo"

Note: if the offset is greater than the string length, the gap is automatically padded with 0x00.

redis 127.0.0.1:6379> setrange greet 6 !
(integer) 7
redis 127.0.0.1:6379> get greet
"hexlo\x00!"
  • append key value
    Purpose: append value to the original value of the key.

  • getrange key start stop
    Purpose: get the value in the string range [start, stop].
    Note: string indexes start from 0 from the left and -1 from the right.

redis 127.0.0.1:6379> set title 'chinese'
OK
redis 127.0.0.1:6379> getrange title 0 3
"chin"
redis 127.0.0.1:6379> getrange title 1 -2
"hines"

Notes:

  1. If start >= length, return an empty string.
  2. If stop >= length, truncate at the end of the string.
  3. If the position of start is to the right of stop, return an empty string.
  • getset key newvalue
    Purpose: get and return the old value, then set the new value.
redis 127.0.0.1:6379> set cnt 0
OK
redis 127.0.0.1:6379> getset cnt 1
"0"
redis 127.0.0.1:6379> getset cnt 2
"1"
  • incr key
    Purpose: increase the value of the specified key by 1 and return the new value.

Notes:

  1. A non-existent key is treated as 0 before INCR.
  2. The range is a signed 64-bit integer.
  • incrby key number
redis 127.0.0.1:6379> incrby age  90
(integer) 92
  • incrbyfloat key floatnumber
redis 127.0.0.1:6379> incrbyfloat age 3.5
"95.5"
  • decr key
redis 127.0.0.1:6379> set age 20
OK
redis 127.0.0.1:6379> decr age
(integer) 19
  • decrby key number
redis 127.0.0.1:6379> decrby age 3
(integer) 16
  • getbit key offset
    Purpose: get the bit at the corresponding position in the binary representation of the value, numbered from 0 from the left.
redis 127.0.0.1:6379> set char A
OK
redis 127.0.0.1:6379> getbit char 1
(integer) 1
redis 127.0.0.1:6379> getbit char 2
(integer) 0
redis 127.0.0.1:6379> getbit char 7
(integer) 1
  • setbit key offset value
    Set the value of the bit corresponding to offset.
    Returns: the old value of that bit.

Notes:

  1. If the offset is too large, zeros are filled in between.
  2. Maximum offset: 2^32 - 1, from which the maximum string size of 512 MB follows.
  • bitop operation destkey key1 [key2 ...]

Apply operation to key1, key2 … keyN, and save the result to destkey.
operation can be AND, OR, NOT, or XOR.

redis 127.0.0.1:6379> setbit lower 7 0
(integer) 0
redis 127.0.0.1:6379> setbit lower 2 1
(integer) 0
redis 127.0.0.1:6379> get lower
" "
redis 127.0.0.1:6379> set char Q
OK
redis 127.0.0.1:6379> get char
"Q"
redis 127.0.0.1:6379> bitop or char char lower
(integer) 1
redis 127.0.0.1:6379> get char
"q"

Note: for NOT, only one source key can be used.

2.2. list

  • rpush key val1 val2

  • lpush key val1 val2

  • linsert key before|after value newValue

  • lpop key

  • lrem key count value

  • ltrim key start end

  • lrange key start end

  • llen key

  • lset key index newValue

  • blpop, brpop

  • lpush key value
    Purpose: insert a value at the head of the list.

  • rpop key
    Purpose: return and delete the tail element of the list.

  • rpush, lpop: omitted.

  • lrange key start stop
    Purpose: return elements in [start, stop] from the list.
    Rule: indexes start from 0 from the left and -1 from the right.

  • lrem key count value
    Purpose: delete elements equal to value from the list at key.
    Note: stop after deleting abs(count) matching values.
    count > 0: delete from the head.
    count < 0: delete from the tail.

  • ltrim key start stop
    Purpose: trim the list corresponding to key to the [start, stop] segment and assign that segment back to key.

  • lindex key index
    Purpose: return the value at index, for example lindex key 2.

  • llen key
    Purpose: count the number of elements in the list.

redis 127.0.0.1:6379> llen task
(integer) 3
redis 127.0.0.1:6379>
  • linsert key after|before search value
    Purpose: find search in the list at key and insert value before or after it.
    Note: the command ends after the first search is found, so it does not insert multiple values.

  • rpoplpush source dest
    Purpose: remove the tail element from source, put it at the head of dest, and return that element.

Scenario: use the task + bak pair of lists to build a safer queue.

Business logic:

  1. RPOPLPUSH task bak.
  2. Receive the returned value and perform business processing.
  3. If successful, remove the task from bak; if unsuccessful, retrieve the task from bak next time.
  • brpop, blpop key timeout
    Purpose: wait to pop the tail/head element of the key.
    timeout is the wait timeout.
    If timeout is 0, wait indefinitely.

Scenario: long-polling Ajax and online chat can use this.

2.2.1. brpop Implementation

Blocking queue: when a client calls brpop, if the server has a data update, it immediately pushes data to the client.

The RedisDb data structure has blocking_keys, which stores the mapping between brpop keys and clients. If data is available, the client waiting on that key is immediately taken out and sent the data; if no data is available, nil is returned after waiting N seconds.

2.3. set

  • sadd key element

  • scard, sismember, srandmember, smembers

  • sdiff, sinter, sunion

  • sadd key value1 value2
    Purpose: add elements to the set at key.

  • srem key value1 value2
    Purpose: delete value1, value2 from the set.
    Return value: the number of elements actually deleted after non-existent elements are ignored.

  • spop key
    Purpose: return and delete one random element from the set at key.

Randomness reflects the unordered nature of a set.

  • srandmember key
    Purpose: return one random element from the set at key.

  • sismember key value
    Purpose: determine whether value is in the set at key; return 1 if yes, 0 if not.

  • smembers key
    Purpose: return all elements in the set.

  • scard key
    Purpose: return the number of elements in the set.

  • smove source dest value
    Purpose: remove value from source and add it to dest.

  • sinter key1 key2 key3
    Purpose: compute and return the intersection of the three sets key1, key2, and key3.

redis 127.0.0.1:6379> sadd s1 0 2 4 6
(integer) 4
redis 127.0.0.1:6379> sadd s2 1 2 3 4
(integer) 4
redis 127.0.0.1:6379> sadd s3 4 8 9 12
(integer) 4
redis 127.0.0.1:6379> sinter s1 s2 s3
1) "4"
redis 127.0.0.1:6379> sinter s3 s1 s2
1) "4"
  • sinterstore dest key1 key2 key3
    Purpose: compute the intersection of key1, key2, and key3 and assign it to dest.

  • sunion key1 key2 .. keyN
    Purpose: compute and return the union of key1, key2 … keyN.

  • sdiff key1 key2 key3
    Purpose: compute the difference between key1 and key2, key3, i.e. key1-key2-key3.

2.4. zset

  • zadd key score element

  • zscore key element

  • zincrby key increScore element

  • zcard key

  • zrange key start end [withscores]

  • zrangebyscore key minScore maxScore

  • zcount key minScore maxScore

  • zremrangebyrank key start end

  • zremrangebyscore key minScore maxScore

  • zadd key score1 value1 score2 value2 ..
    Add elements.

redis 127.0.0.1:6379> zadd stu 18 lily 19 hmm 20 lilei 21 lilei
(integer) 3
  • zrem key value1 value2 ..
    Purpose: delete elements from the set.

  • zremrangebyscore key min max
    Purpose: delete elements by score; delete elements whose score is in [min,max].

redis 127.0.0.1:6379> zremrangebyscore stu 4 10
(integer) 2
redis 127.0.0.1:6379> zrange stu 0 -1
1) "f"
  • zremrangebyrank key start end
    Purpose: delete elements by rank; delete ranks in [start,end].
redis 127.0.0.1:6379> zremrangebyrank stu 0 1
(integer) 2
redis 127.0.0.1:6379> zrange stu 0 -1
1) "c"
2) "e"
3) "f"
4) "g"
  • zrank key member
    Query the rank of member in ascending order, starting at rank 0.

  • zrevrank key member
    Query the rank of member in descending order, starting at rank 0.

  • ZRANGE key start stop [WITHSCORES]
    After sorting the set, return elements with ranks [start,stop].
    Ascending order by default.
    WITHSCORES also prints the scores.

  • zrevrange key start stop
    Purpose: sort the set in descending order and return elements with ranks [start,stop].

  • zrangebyscore key min max [withscores] limit offset N
    Purpose: after sorting the set in ascending order, get elements whose scores are within [min,max], skip offset elements, and take N elements.

redis 127.0.0.1:6379> zadd stu 1 a 3 b 4 c 9 e 12 f 15 g
(integer) 6
redis 127.0.0.1:6379> zrangebyscore stu 3 12 limit 1 2 withscores
1) "c"
2) "4"
3) "e"
4) "9"
  • zcard key
    Return the number of elements.

  • zcount key min max
    Return the number of elements in the [min,max] score range.

  • zinterstore destination numkeys key1 [key2 ...]
    [WEIGHTS weight [weight ...]]
    [AGGREGATE SUM|MIN|MAX]

Compute the intersection of key1, key2; their weights are weight1, weight2.
The aggregation method is sum | min | max.
The aggregation result is stored in the destination set.

Note: how should WEIGHTS and AGGREGATE be understood?
Answer: if there is an intersection, the intersecting elements also have scores. How should the scores be handled?
AGGREGATE SUM -> add the scores; MIN -> take the minimum score; MAX -> take the maximum score.

Also, different key weights can be set using WEIGHTS; during intersection, score * weight is used.

See the following example:

redis 127.0.0.1:6379> zadd z1 2 a 3 b 4 c
(integer) 3
redis 127.0.0.1:6379> zadd z2 2.5 a 1 b 8 d
(integer) 3
redis 127.0.0.1:6379> zinterstore tmp 2 z1 z2
(integer) 2
redis 127.0.0.1:6379> zrange tmp 0 -1
1) "b"
2) "a"
redis 127.0.0.1:6379> zrange tmp 0 -1 withscores
1) "b"
2) "4"
3) "a"
4) "4.5"
redis 127.0.0.1:6379> zinterstore tmp 2 z1 z2 aggregate sum
(integer) 2
redis 127.0.0.1:6379> zrange tmp 0 -1 withscores
1) "b"
2) "4"
3) "a"
4) "4.5"
redis 127.0.0.1:6379> zinterstore tmp 2 z1 z2 aggregate min
(integer) 2
redis 127.0.0.1:6379> zrange tmp 0 -1 withscores
1) "b"
2) "1"
3) "a"
4) "2"
redis 127.0.0.1:6379> zinterstore tmp 2 z1 z2 weights 1 2
(integer) 2
redis 127.0.0.1:6379> zrange tmp 0 -1 withscores
1) "b"
2) "5"
3) "a"
4) "7"

2.5. hash

  • hget, hset, hdel

  • hexists, hlen

  • hmget, hmset

  • hgetall, hvals, hkeys

  • hset key field value
    Purpose: set the value of the field in key to value.
    Note: if the field does not exist, add it directly; if it exists, overwrite its old value.

  • hmset key field1 value1 [field2 value2 field3 value3 ......fieldN valueN]
    Purpose: set fields field1 -> N with corresponding values value1 -> N.
    (In PHP terms: $key = array(field1=>value1, field2=>value2 ....fieldN=>valueN).)

  • hget key field
    Purpose: return the value of field in key.

  • hmget key field1 field2 fieldN
    Purpose: return the values of field1, field2, fieldN in key.

  • hgetall key
    Purpose: return all fields and their values in key.

  • hdel key field
    Purpose: delete field from key.

  • hlen key
    Purpose: return the number of fields in key.

  • hexists key field
    Purpose: determine whether field exists in key.

  • hincrby key field value
    Purpose: increase the value of field in key by the integer value.

  • hincrbyfloat key field value
    Purpose: increase the value of field in key by the floating-point value.

  • hkeys key
    Purpose: return all fields in key.

  • hvals key
    Purpose: return all values in key.

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub