Table of Contents
Introduction to Redis data structure
List list
Set Collection
Hash hashing
Zset有序集合
Home Database Redis Let's talk in depth about the 5 basic data types in Redis

Let's talk in depth about the 5 basic data types in Redis

Nov 23, 2021 pm 06:56 PM
redis Basic data types

This article will give you a detailed understanding of the 5 basic data types in Redis (String string, List list, Set collection, Hash hash, Zset ordered collection), I hope it will be helpful to you!

Let's talk in depth about the 5 basic data types in Redis

Introduction to Redis data structure

For redis, all keys are strings. When we talk about basic data structures, we discuss the data types for storing values, which mainly include 5 common data types: String, List, Set, Zset, and Hash. [Related recommendations: Redis video tutorial]

Lets talk in depth about the 5 basic data types in Redis

##Structure typeThe value stored in the structure Structure reading and writing capabilitiescan be a string or an integer or floating point number Operate on the entire string or a part of the string; perform increment or decrement operation on integer or floating point number; A linked list, each node on the linked list contains a stringPerform push and pop operations on both ends of the linked list, and read single or multiple elements; according to Value finds or deletes elements; An unordered collection containing stringsA collection of strings, Basic methods include checking whether there is addition, acquisition, and deletion; it also includes calculation of intersection, union, difference, etc.Unordered hash table containing key-value pairsContains methods for adding, getting, and deleting single elementsSame as hashing, used to store key-value pairsOrdered mapping between string members and floating point scores; the order of elements is determined by the size of the scores; the inclusion method has been added , obtain, delete a single element and obtain elements based on score range or member
String string
List List
Set collection
Hash hash
Zset ordered set

Detailed explanation of basic data structure

## String

String is the most basic data type in redis. One key corresponds to one value.

The String type is binary safe, which means that the string of redis can contain any data. Such as numbers, strings, jpg images or serialized objects.

    Command usage
CommandGETSETDELINCRDECRINCRBYDECRBY
  • Command execution
127.0.0.1:6379> set hello world
OK
127.0.0.1:6379> get hello
"world"
127.0.0.1:6379> del hello
(integer) 1
127.0.0.1:6379> get hello
(nil)
127.0.0.1:6379> get counter
"2"
127.0.0.1:6379> incr counter
(integer) 3
127.0.0.1:6379> get counter
"3"
127.0.0.1:6379> incrby counter 100
(integer) 103
127.0.0.1:6379> get counter
"103"
127.0.0.1:6379> decr counter
(integer) 102
127.0.0.1:6379> get counter
"102"
Copy after login
  • Actual scenario
    • Cache: Classic usage scenario, common information , strings, pictures or videos and other information are placed in redis. Redis serves as the cache layer and mysql serves as the persistence layer to reduce the read and write pressure of mysql.
    • Counter: redis is a single-threaded model. One command will not be executed until the next one is executed. At the same time, the data can be transferred to other data sources in one step.
    • session: A common solution is spring session redis to implement session sharing,

List list

List in Redis is actually a linked list (Redis uses a double-ended linked list to implement List).

Using the List structure, we can easily implement the latest message queuing function (such as Sina Weibo's TimeLine). Another application of List is the message queue. You can use the PUSH operation of List to store tasks in the List, and then the worker thread uses the POP operation to take out the tasks for execution.

  • Command usage
Brief description Get the value stored in a given key using
GET name
Set the value stored in the given key SET name value
Delete The value stored in the given key DEL name
Increase the value stored by the key by 1 INCR key
Decrease the value stored in the key by 1 DECR key
Add the integer to the value stored in the key INCRBY key amount
Subtract the integer from the value stored in the key DECRBY key amount
CommandBrief description Use
RPUSH to push the given value to the right end of the listRPUSH key value
LPUSHPush the given value to the left end of the listLPUSH key value
RPOP Pops a value from the right end of the list and returns the popped valueRPOP key
LPOPPops a value from the left end of the list and returns Return the popped valueLPOP key
LRANGEGet all values ​​in the list in the given rangeLRANGE key 0 -1
LINDEXGet the element in the list by index. You can also use negative subscripts, with -1 representing the last element of the list, -2 representing the penultimate element of the list, and so on. LINEX key index
  • Tips for using lists
    • lpush lpop=Stack(stack)
    • lpush rpop=Queue (queue)
    • lpush ltrim=Capped Collection (limited collection)
    • lpush brpop=Message Queue (message queue)
  • Command execution
127.0.0.1:6379> lpush mylist 1 2 ll ls mem
(integer) 5
127.0.0.1:6379> lrange mylist 0 -1
1) "mem"
2) "ls"
3) "ll"
4) "2"
5) "1"
127.0.0.1:6379> lindex mylist -1
"1"
127.0.0.1:6379> lindex mylist 10        # index不在 mylist 的区间范围内
(nil)
Copy after login
  • Actual scenario
    • Weibo TimeLine: Someone posts on Weibo, uses lpush to add to the timeline, and displays New list information.
    • Message Queue

Set Collection

Redis’ Set is An unordered collection of type String. Set members are unique, which means that duplicate data cannot appear in the set.

Collections in Redis are implemented through hash tables, so the complexity of adding, deleting, and searching is O(1).

  • Command usage
CommandBrief description Add one or more members to the collection using
SADDSADD key value
SCARDGet the number of members in the setSCARD key
SMEMBERReturn all members in the set SMEMBER key member
SISMEMBERDetermine whether the member element is a member of the set keySISMEMBER key member

For other set operations, please refer here

https://www.runoob.com/redis/redis-sets.html

  • Command execution
127.0.0.1:6379> sadd myset ycf ycf1 xiao ycf
(integer) 3
127.0.0.1:6379> smember myset
1) "xiao"
2) "ycf1"
3) "ycf"
127.0.0.1:6379> sismember myset ycf
(integer) 1
Copy after login
  • Actual scenario
    • Tag (tag), add to the user Tags, or users add tags to messages, so that those with the same tag or similar tags can recommend things or people to follow.
    • Like, dislike, collect, etc. can be placed in the set to achieve

Hash hashing

Redis hash is a mapping table of string type fields and values. Hash is particularly suitable for storing objects.

  • Command usage
##CommandBrief descriptionUse##HSETHGETHGETALLHDEL
  • 命令执行
127.0.0.1:6379> hset user name1 ycf
(integer) 1
127.0.0.1:6379> hset user email1 ycf@163.com
(integer) 1
127.0.0.1:6379> hgetall user
1) "name1"
2) "ycf"
3) "email1"
4) "ycf@163.com"
127.0.0.1:6379> hget user user
(nil)
127.0.0.1:6379> hget user name1
"ycf"
127.0.0.1:6379> hset user name2 xiaoycf
(integer) 1
127.0.0.1:6379> hset user email2 xiaoycf@163.com
(integer) 1
127.0.0.1:6379> hgetall user
1) "name1"
2) "ycf"
3) "email1"
4) "ycf@163.com"
5) "name2"
6) "xiaoycf"
7) "email2"
8) "xiaoycf@163.com"
Copy after login
  • 实战场景
    • 缓存: 能直观,相比string更节省空间,的维护缓存信息,如用户信息,视频信息等。

Zset有序集合

Redis 有序集合和集合一样也是 string 类型元素的集合,且不允许重复的成员。不同的是每个元素都会关联一个 double 类型的分数。redis 正是通过分数来为集合中的成员进行从小到大的排序。

有序集合的成员是唯一的,但分数(score)却可以重复。集合是通过哈希表实现的,所以添加,删除,查找的复杂度都是 O(1)。

  • 命令使用
Add key-value pairHSET hash-key sub-key1 value1
Get the value of the specified hash keyHGET hash-key key1
Get all key-value pairs contained in the hash HGETALL hash-key
If the given key exists in the hash , then remove this keyHDEL hash-key sub-key1
命令简述使用
ZADD将一个带有给定分值的成员添加到哦有序集合里面ZADD zset-key 178 member1
ZRANGE根据元素在有序集合中所处的位置,从有序集合中获取多个元素ZRANGE zset-key 0-1 withccores
ZREM如果给定元素成员存在于有序集合中,那么就移除这个元素ZREM zset-key member1

更多命令请参考这里

https://www.runoob.com/redis/redis-sorted-sets.html

  • 命令执行
127.0.0.1:6379> zadd myscoreset 100 ycf 90 xiaoycf
(integer) 2
127.0.0.1:6379> ZRANGE myscoreset 0 -1
1) "xiaoycf"
2) "ycf"
127.0.0.1:6379> ZSCORE myscoreset ycf
"100"
Copy after login
  • 实战场景
    • 排行榜:有序集合经典使用场景。例如小说视频等网站需要对用户上传的小说视频做排行榜,榜单可以按照用户关注数,更新时间,字数等打分,做排行。

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Let's talk in depth about the 5 basic data types 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 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 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 use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

How to use redis lock How to use redis lock Apr 10, 2025 pm 08:39 PM

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

How to read the source code of redis How to read the source code of redis Apr 10, 2025 pm 08:27 PM

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

How to solve data loss with redis How to solve data loss with redis Apr 10, 2025 pm 08:24 PM

Redis data loss causes include memory failures, power outages, human errors, and hardware failures. The solutions are: 1. Store data to disk with RDB or AOF persistence; 2. Copy to multiple servers for high availability; 3. HA with Redis Sentinel or Redis Cluster; 4. Create snapshots to back up data; 5. Implement best practices such as persistence, replication, snapshots, monitoring, and security measures.

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.

See all articles