Home Database Redis Detailed explanation of key related commands in redis

Detailed explanation of key related commands in redis

Nov 27, 2019 pm 05:03 PM
redis

Detailed explanation of key related commands in redis

1. Overview:

This article will mainly describe the Redis commands related to Key. Learning these commands is a very important foundation for learning Redis, and it is also a powerful tool to fully tap the potential of Redis. (Recommended: redis video tutorial)

2. Related command list:

Command prototype Time complexity Command description Return value
KEYS pattern O(N) The N in time complexity represents the number of Keys in the database. Get all Keys matching the pattern parameter. It should be noted that we should try to avoid calling this command in our normal operations, because for large databases, this command is very time-consuming and has a relatively large impact on the performance of the Redis server. pattern supports glob-style wildcard format, such as * represents any one or more characters, ? represents any character, and [abc] represents any letter in square brackets. List of keys matching the pattern.
DEL key [key ...] O(N) The N in time complexity represents the number of deleted Keys. Delete the keys specified in the parameters from the database. If the specified key does not exist, it will be ignored. It should also be pointed out that if the data type associated with the specified Key is not a String type, but a container type such as List, Set, Hashes, and Sorted Set, the time complexity of this command to delete each key is O(M), where M represents the number of elements in the container. For String type Key, its time complexity is O(1). The actual number of deleted Keys.
EXISTS key O(1) Determine whether the specified key exists. 1 means it exists, 0 means it doesn't exist.
MOVE key db O(1) Move the key specified in the current database to the database specified in the parameter. If the key already exists in the target database, or does not exist in the current database, this command will do nothing and return 0. Returns 1 if the move is successful, otherwise 0.
RENAME key newkey O(1) Rename the specified key. If the two Keys commands in the parameters are the same, Or the source Key does not exist, this command will return relevant error information. If newKey already exists, it will be overwritten directly.
RENAMENX key newkey O(1) If the new value does not exist, the original value in the parameter will be Modify to new value. Other conditions are consistent with RENAME. 1 means the modification is successful, otherwise 0.
PERSIST key O(1) If the Key has an expiration time, this command will eliminate its expiration time so that the Key will no longer There are timeouts, but persistent storage is possible. 1 means that the Key's expiration time has been removed, 0 means that the Key does not exist or has no expiration time.
EXPIRE key seconds O(1) This command sets the timeout seconds for the Key specified in the parameter. Afterwards, the Key is automatically deleted. If the Key is modified before the timeout occurs, the timeout associated with the key will be removed. 1 means the timeout is set, 0 means the Key does not exist or cannot be set.
EXPIREAT key timestamp O(1) The logical function of this command is exactly the same as EXPIRE, the only difference is the timeout specified by the command Time is absolute time, not relative time. The time parameter is in Unix timestamp format, which is the number of seconds that have elapsed since January 1, 1970. 1 indicates that the timeout is set, 0 indicates that the Key does not exist or cannot be set.
TTL key O(1) Get the remaining timeout description of the key. Returns the remaining description. If the key does not exist or has no timeout setting, it returns -1.
RANDOMKEY O(1) Randomly returns a Key from the currently opened database. The random key returned, or nil if the database is empty.
TYPE key O(1) Get the type of value associated with the key specified in the parameter. This command will return it in string format . The returned strings are string, list, set, hash and zset. If the key does not exist, none is returned.
SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC|DESC] [ALPHA] [STORE destination] O(N M*log(M)) This command is relatively complex, so we only give the most basic usage here. Interested netizens can refer to the official documentation of redis. Return the sorted original list.

3. Command examples:

1. KEYS/RENAME/DEL/EXISTS/MOVE/RENAMENX:

    #在Shell命令行下启动Redis客户端工具。
    /> redis-cli
    #清空当前选择的数据库,以便于对后面示例的理解。
    redis 127.0.0.1:6379> flushdb
    OK
    #添加String类型的模拟数据。
    redis 127.0.0.1:6379> set mykey 2
    OK
    redis 127.0.0.1:6379> set mykey2 "hello"
    OK
    #添加Set类型的模拟数据。
    redis 127.0.0.1:6379> sadd mysetkey 1 2 3
    (integer) 3
    #添加Hash类型的模拟数据。
    redis 127.0.0.1:6379> hset mmtest username "stephen"
    (integer) 1
    #根据参数中的模式,获取当前数据库中符合该模式的所有key,从输出可以看出,该命令在执行时并不区分与Key关联的Value类型。
    redis 127.0.0.1:6379> keys my*
    1) "mysetkey"
    2) "mykey"
    3) "mykey2"
    #删除了两个Keys。
    redis 127.0.0.1:6379> del mykey mykey2
    (integer) 2
    #查看一下刚刚删除的Key是否还存在,从返回结果看,mykey确实已经删除了。
    redis 127.0.0.1:6379> exists mykey
    (integer) 0
    #查看一下没有删除的Key,以和上面的命令结果进行比较。
    redis 127.0.0.1:6379> exists mysetkey
    (integer) 1
    #将当前数据库中的mysetkey键移入到ID为1的数据库中,从结果可以看出已经移动成功。
    redis 127.0.0.1:6379> move mysetkey 1
    (integer) 1
    #打开ID为1的数据库。
    redis 127.0.0.1:6379> select 1
    OK
    #查看一下刚刚移动过来的Key是否存在,从返回结果看已经存在了。
    redis 127.0.0.1:6379[1]> exists mysetkey
    (integer) 1
    #在重新打开ID为0的缺省数据库。
    redis 127.0.0.1:6379[1]> select 0
    OK
    #查看一下刚刚移走的Key是否已经不存在,从返回结果看已经移走。
    redis 127.0.0.1:6379> exists mysetkey
    (integer) 0
    #准备新的测试数据。    
    redis 127.0.0.1:6379> set mykey "hello"
    OK
    #将mykey改名为mykey1
    redis 127.0.0.1:6379> rename mykey mykey1
    OK
    #由于mykey已经被重新命名,再次获取将返回nil。
    redis 127.0.0.1:6379> get mykey
    (nil)
    #通过新的键名获取。
    redis 127.0.0.1:6379> get mykey1
    "hello"
    #由于mykey已经不存在了,所以返回错误信息。
    redis 127.0.0.1:6379> rename mykey mykey1
    (error) ERR no such key
    #为renamenx准备测试key
    redis 127.0.0.1:6379> set oldkey "hello"
    OK
    redis 127.0.0.1:6379> set newkey "world"
    OK
    #由于newkey已经存在,因此该命令未能成功执行。
    redis 127.0.0.1:6379> renamenx oldkey newkey
    (integer) 0
    #查看newkey的值,发现它也没有被renamenx覆盖。
    redis 127.0.0.1:6379> get newkey
    "world"
Copy after login

2. PERSIST/EXPIRE/EXPIREAT/TTL:

    #为后面的示例准备的测试数据。
    redis 127.0.0.1:6379> set mykey "hello"
    OK
    #将该键的超时设置为100秒。
    redis 127.0.0.1:6379> expire mykey 100
    (integer) 1
    #通过ttl命令查看一下还剩下多少秒。
    redis 127.0.0.1:6379> ttl mykey
    (integer) 97
    #立刻执行persist命令,该存在超时的键变成持久化的键,即将该Key的超时去掉。
    redis 127.0.0.1:6379> persist mykey
    (integer) 1
    #ttl的返回值告诉我们,该键已经没有超时了。
    redis 127.0.0.1:6379> ttl mykey
    (integer) -1
    #为后面的expire命令准备数据。
    redis 127.0.0.1:6379> del mykey
    (integer) 1
    redis 127.0.0.1:6379> set mykey "hello"
    OK
    #设置该键的超时被100秒。
    redis 127.0.0.1:6379> expire mykey 100
    (integer) 1
    #用ttl命令看一下当前还剩下多少秒,从结果中可以看出还剩下96秒。
    redis 127.0.0.1:6379> ttl mykey
    (integer) 96
    #重新更新该键的超时时间为20秒,从返回值可以看出该命令执行成功。
    redis 127.0.0.1:6379> expire mykey 20
    (integer) 1
    #再用ttl确认一下,从结果中可以看出果然被更新了。
    redis 127.0.0.1:6379> ttl mykey
    (integer) 17
    #立刻更新该键的值,以使其超时无效。
    redis 127.0.0.1:6379> set mykey "world"
    OK
    #从ttl的结果可以看出,在上一条修改该键的命令执行后,该键的超时也无效了。
    redis 127.0.0.
    1:6379> ttl mykey
      (integer) -1
Copy after login

3. TYPE/RANDOMKEY/SORT:

    #由于mm键在数据库中不存在,因此该命令返回none。
    redis 127.0.0.1:6379> type mm
    none
    #mykey的值是字符串类型,因此返回string。
    redis 127.0.0.1:6379> type mykey
    string
    #准备一个值是set类型的键。
    redis 127.0.0.1:6379> sadd mysetkey 1 2
    (integer) 2
    #mysetkey的键是set,因此返回字符串set。
    redis 127.0.0.1:6379> type mysetkey
    set
    #返回数据库中的任意键。
    redis 127.0.0.1:6379> randomkey
    "oldkey"
    #清空当前打开的数据库。
    redis 127.0.0.1:6379> flushdb
    OK
    #由于没有数据了,因此返回nil。
    redis 127.0.0.1:6379> randomkey
    (nil)
Copy after login

For more redis knowledge, please pay attention redis introductory tutorial column.

The above is the detailed content of Detailed explanation of key related commands in redis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to set the redis expiration policy How to set the redis expiration policy Apr 10, 2025 pm 10:03 PM

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

How to implement redis counter How to implement redis counter Apr 10, 2025 pm 10:21 PM

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

See all articles