Redis Common Commands

Time: Column:Backend & Servers views:261

1. Introduction

In modern application development, fast data reading and writing as well as efficient storage are key to ensuring system performance. Redis, as an open-source in-memory data storage system, is widely used in various scenarios such as caching, real-time data processing, and message queues due to its high performance and rich data structures. It can store multiple data types such as strings, hashes, lists, sets, and sorted sets, and supports a wide range of operation commands, greatly enhancing the flexibility and efficiency of developers.

In practical development, mastering common Redis commands is fundamental to effectively utilizing this powerful tool. Whether building high-concurrency web applications or handling large data sets, understanding how to operate data, manage caches, and monitor performance with Redis commands is crucial. These commands not only simplify the data access process but also offer powerful features like transactions, publish/subscribe mechanisms, and persistence options, allowing developers to focus more on implementing business logic.

This blog will delve into common Redis commands to help readers better understand how to effectively apply these commands in different scenarios. We will gradually introduce the purpose, basic syntax, and usage examples of each command, enabling you to quickly get started in practical development. Additionally, we will share best practices to help you avoid common pitfalls when using Redis, thereby improving system performance and reliability. We hope this blog helps you master Redis usage skills, optimize your application architecture, and provide users with a smoother experience.

Redis Common Commands


2. Summary of Common Redis Commands

2.1 Global Commands Summary

  • keys: Returns all keys that match the pattern. The following patterns are supported:

    • h?llo: Matches "hello", "hallo", and "hxllo" (where "?" represents any single character).

    • h*llo: Matches "hllo" and "heeeello" (where "*" represents any number of characters, including zero).

    • h[ae]llo: Matches "hello" and "hallo" but not "hillo" (where "[ae]" represents any character that is either "a" or "e").

    • h[^e]llo: Matches "hallo", "hbllo", etc., but not "hello" (where "[^e]" represents any character except "e").

    • h[a-b]llo: Matches "hallo" and "hbllo" (where "[a-b]" represents any character between "a" and "b", including "a" and "b").

  • exists: Checks if a key exists.

  • del: Deletes the specified key.

  • expire: Sets an expiration time for a specified key in seconds.

  • ttl: Queries the expiration time of a key in seconds.

  • type: Returns the data type of the corresponding key.

  • object encoding: Queries the internal encoding of a value.

  • setnx: Sets the key-value pair only if the key does not already exist.

2.2 String Type Commands Summary

CommandEffectTime Complexity
set key valueSets the value of a key to valueO(1)
`set key value [ex secondspx milliseconds] [nxxx] [keepttl]`
get keyRetrieves the value of a keyO(1)
del key [key ...]Deletes the specified key(s)O(k), where k is the number of keys
mset key value [key value ...]Sets multiple key-value pairsO(k), where k is the number of keys
mget key [key ...]Retrieves values for multiple keysO(k), where k is the number of keys
incr keyIncrements the value of the specified key by 1O(1)
decr keyDecrements the value of the specified key by 1O(1)
incrby key nIncrements the value of the specified key by nO(1)
decrby key nDecrements the value of the specified key by nO(1)
incrbyfloat key nIncrements the value of the specified key by n (float)O(1)
append key valueAppends value to the value of the specified keyO(1)
strlen keyRetrieves the length of the value of the specified keyO(1)
setrange key offset valueOverwrites part of the value of a specified key starting from offsetO(n), where n is the string length, typically O(1)
getrange key start endRetrieves part of the value of the specified key from start to endO(n), where n is the string length, typically O(1)

2.3 set key value [ex seconds|px milliseconds] [nx|xx] [keepttl]

This is an extended form of the set command in Redis, allowing you to specify additional options when setting key-value pairs. The specific meaning is as follows:

  • key: The key to be set.

  • value: The value associated with the key.

  • [ex seconds]: Optional parameter to set the expiration time of the key in seconds.

  • [px milliseconds]: Optional parameter to set the expiration time of the key in milliseconds.

  • [nx]: Optional parameter that sets the key only if it does not already exist.

  • [xx]: Optional parameter that updates the key only if it already exists.

  • [keepttl]: Optional parameter that preserves the remaining time to live of the key when updating its value.

These options allow you to flexibly control the setting and expiration behavior of keys.


2.4 Hash Type Commands Summary

CommandEffectTime Complexity
hset key field valueSets the value of a field in a hashO(1)
hget key fieldRetrieves the value of a field in a hashO(1)
hdel key field [field ...]Deletes one or more fields in a hashO(k), where k is the number of fields
hlen keyReturns the number of fields in a hashO(1)
hgetall keyRetrieves all field-value pairs in a hashO(k), where k is the number of fields
hmget key field [field ...]Retrieves multiple field-values from a hashO(k), where k is the number of fields
hmset key field value [field value ...]Sets multiple field-values in a hashO(k), where k is the number of fields
hexists key fieldChecks if a field exists in a hashO(1)
hkeys keyRetrieves all field names in a hashO(k), where k is the number of fields
hvals keyRetrieves all values in a hashO(k), where k is the number of values
hsetnx key field valueSets the value of a field only if the field does not existO(1)
hincrby key field nIncrements the value of a field in a hash by nO(1)
hincrbyfloat key field nIncrements the value of a field in a hash by n (float)O(1)
hstrlen key fieldRetrieves the length of the value in a fieldO(1)

2.5 List Type Commands Summary

Operation TypeCommandTime Complexity
Addrpush key value [value ...]O(k), where k is the number of elements

lpush key value [value ...]O(k), where k is the number of elements

linsert key beforeafter pivot value
Searchlrange key start endO(s + n), where s is the start offset and n is the range from start to end

lindex key indexO(n), where n is the index offset

llen keyO(1)
Deletelpop keyO(1)

rpop keyO(1)

lrem key count valueO(k), where k is the number of elements

ltrim key start endO(k), where k is the number of elements
Modifylset key index valueO(n), where n is the index offset
Blockingblpop brpopO(1)

2.6 Set Type Commands Summary

CommandEffectTime Complexity
sadd key element [element ...]Add one or more elements to the set. Duplicate elements cannot be added.O(k), where k is the number of elements
srem key element [element ...]Remove one or more specified elements from the set.O(k), where k is the number of elements
scard keyReturn the number of elements in the set.O(1)
sismember key elementCheck if an element exists in the set, returns 1 if it exists, 0 if not.O(1)
srandmember key [count]Return one or more random elements from the set without removing them. If count is provided, return multiple random elements.O(n), where n is count
spop key [count]Remove and return count number of random elements from the set.O(n), where n is count
smembers keyReturn all elements of the set.O(k), where k is the number of elements
sinter key [key ...]Return the intersection of one or more sets.O(m * k), where k is the smallest number of elements in the sets and m is the number of keys
sinterstore destination key [key ...]Store the intersection of the given sets in the destination set.O(N * M), where N is the smallest number of elements in the sets and M is the largest
sunion key [key ...]Return the union of one or more sets.O(k), where k is the total number of elements in all sets
sunionstore destination key [key ...]Store the union of the given sets in the destination set.O(N), where N is the total number of elements in all sets
sdiff key [key ...]Return the difference of one or more sets.O(k), where k is the total number of elements in all sets
sdiffstore destination key [key ...]Store the difference of the given sets in the destination set.O(N), where N is the total number of elements in all sets

2.7 Sorted Set Type Commands Summary

CommandEffectTime Complexity
zadd key score member [score member ...]Add or update specified elements with associated scores in a sorted set.O(k * log(n)), where k is the number of members added, n is the number of elements in the current sorted set
zcard keyGet the number of elements in the sorted set.O(1)
zscore key memberReturn the score of the specified element.O(1)
zrank key memberReturn the rank of the specified element, in ascending order.O(log(n)), where n is the number of elements in the sorted set
zrevrank key memberReturn the rank of the specified element, in descending order.O(log(n)), where n is the number of elements in the sorted set
zrem key member [member ...]Remove specified elements from the sorted set.O(k * log(n)), where k is the number of members deleted, n is the number of elements in the sorted set
zincrby key increment memberAdd the specified score to the associated score of the element.O(log(n)), where n is the number of elements in the sorted set
zrange key start stop [withscores]Return elements in the specified range, in ascending order of scores. Can return scores if "withscores" is included.O(k + log(n)), where k is the number of elements retrieved, n is the number of elements in the sorted set
zrevrange key start stop [withscores]Return elements in the specified range, in descending order of scores. Can return scores if "withscores" is included.O(k + log(n)), where k is the number of elements retrieved, n is the number of elements in the sorted set
zrangebyscore key min max [withscores]Return elements with scores between min and max. By default, min and max are inclusive. Use '(' to exclude them. Can return scores if "withscores" is included.O(k + log(n)), where k is the number of elements retrieved, n is the number of elements in the sorted set
zrevrangebyscore key max min [withscores]Return elements with scores between max and min, in descending order. Can return scores if "withscores" is included.O(k + log(n)), where k is the number of elements retrieved, n is the number of elements in the sorted set
zpopmax key [count]Remove and return the count highest-scored elements.O(log(N) * M)
zpopmin key [count]Remove and return the count lowest-scored elements.O(log(N) * M)
bzpopmax key [count] timeoutBlocking version of zpopmax.O(log(N))
bzpopmin key [count] timeoutBlocking version of zpopmin.O(log(N))
zcount key min maxReturn the number of elements with scores between min and max. By default, min and max are inclusive. Use '(' to exclude them.O(log(n)), where n is the number of elements in the sorted set
zremrangebyrank key start stopRemove elements in the specified range by rank, inclusive.O(k + log(n)), where k is the number of elements removed, n is the number of elements in the sorted set
zremrangebyscore key min maxRemove elements in the specified range by score, inclusive.O(k + log(n)), where k is the number of elements removed, n is the number of elements in the sorted set
zinterstore destination numkeys key [key ...] [weights weight[weight ...]] [aggregate <summinmax>]
zunionstore destination numkeys key [key ...] [weights weight[weight ...]] [aggregate <summinmax>]

2.8 zadd key score member [score member ...]
Add or update specified elements with associated scores in a sorted set. Scores must be of type double. +inf and -inf are also valid as extreme limits.

Options for ZADD:

  • XX: Only updates existing elements; does not add new ones.

  • NX: Only adds new elements; does not update existing ones.

  • CH: Includes the count of updated elements (default is the count of added elements).

  • INCR: Increments the score of the element by the specified value, similar to zincrby. Only one element and score can be specified.
    Syntax: zadd key [NX | XX] [GT | LT] [CH] [INCR] score member [score member ...]

2.9 Difference Between Lists, Sets, and Sorted Sets

Data StructureAllows Duplicate ElementsOrderedOrder BasisApplication Scenarios
ListYesYesIndexTimeline, Message Queue, etc.
SetNoNoTags, Social Networks, etc.
Sorted SetNoYesScoreLeaderboards, Social Networks, etc.





3. Summary

In this article, we systematically introduced the commonly used Redis commands and their specific applications, covering the operation methods for different data types such as strings, hashes, sets, and sorted sets. At the same time, we delved into Redis's key management, expiration mechanisms, and persistence strategies, helping developers better master the core functionalities and usage scenarios of Redis. At the application level, Redis, with its efficient read/write performance, rich data structures, and flexible operation commands, has become a powerful tool for solving high concurrency and large-scale data access problems. Through these examples and analyses, we believe readers have gained a deeper understanding of Redis's use and can leverage its advantages more effectively in their projects.


4. Conclusion

Redis is not only a reflection of technology but also a tool for innovative thinking. Whether it's improving system performance or optimizing data storage and processing, Redis opens the door to more possibilities for developers. On the technological path ahead, every challenge is an opportunity for growth. By maintaining passion and focus for technology, and continuously learning and practicing, you will eventually find your own brilliance in the world of code. Just as Redis is simple yet powerful, we too can create more efficient and intelligent systems through continuous accumulation, reaching our own technological peaks. Keep it up!