[Share] Five basic data types and application scenarios of Redis

Foreword:

Redis supports five basic data types:

  1. String (string type): It can be an ordinary string, an integer or a floating point value. You can set the expiration time; you can perform append, get, set, incr, decr and other operations on strings.
  2. Hash (hash type): Similar to an array, each element is a key-value pair of field and value. Operations such as adding, deleting, checking, and modifying can be performed on the entire hash table or a single element.
  3. List (list type): A linked list, each node in the linked list contains a string. Operations such as pop and push can be performed on the head and tail of the linked list.
  4. Set (collection type): An unordered collection similar to a list that supports operations such as adding, deleting, and searching. Each element in the collection is unique.
  5. Zset (ordered set type): It is also an unordered set. Unlike set, each element will be associated with a score, and the score can make the elements in the set sorted according to certain rules. Operations such as increasing or decreasing the fraction of elements in the collection can be performed.

The characteristics and methods of the above five basic data types are different, and you can choose according to your specific needs.

insert image description here


String String type:

Strings in Redis can be any binary data, such as JPEG images or JSON objects, etc. The string type is mainly used in scenarios such as caching, counting, and current limiting.

The following are some characteristics of the String type of Redis:

  • Redis's String type can store any form of string, including binary data.
  • The String type of Redis has very efficient storage and access speed, and supports routine operations such as reading, writing, appending, and deleting.
  • The String type of Redis also supports some special functions, such as performing self-increment or self-decrement operations on specified strings, or performing bit operations on strings.

1. String

Strings in Redis can be any binary data, such as JPEG images or JSON objects, etc. The string type is mainly used in scenarios such as caching, counting, and current limiting.

# 设置一个字符串
> SET name "Alice"
OK

# 获取字符串
> GET name
"Alice"

# 修改字符串
> SET name "Bob"
OK

# 获取修改后的字符串
> GET name
"Bob"

2. Integer

Redis strings can also store numbers, which can be incremented or decremented. These operations are atomic and can be used in scenarios such as counters and leaderboards.

# 将一个整数设置到key中
> SET count 10
OK

# 自增
> INCR count
11

# 自减
> DECR count
10

# 自增指定的值
> INCRBY count 5
15

# 自减指定的值
> DECRBY count 2
13

3. Floating point numbers

Redis strings can also store floating-point numbers, which can do various complex calculations, such as score rankings, etc.

# 设置一个浮点数
> SET balance 100.0
OK

# 自增指定的浮点数
> INCRBYFLOAT balance 25.5
125.5

# 自减指定的浮点数
> INCRBYFLOAT balance -50.0
75.5

Hash Hash type

The Hash type of Redis is a data type that stores key-value pairs, similar to Map or Dictionary in other programming languages. It allows storing multiple fields and corresponding values ​​under one Redis key, and can quickly read the values ​​of a single field or multiple fields.

Here is an example of a simple Redis Hash type:

# 创建一个名为user的Hash类型
> HSET user name "John" age 30 email "[email protected]"
(integer) 3

# 获取user中的所有字段和对应的值
> HGETALL user
1) "name"
2) "John"
3) "age"
4) "30"
5) "email"
6) "[email protected]"

# 获取user中的name字段的值
> HGET user name
"John"

# 获取user中的age和email字段的值
> HMGET user age email
1) "30"
2) "[email protected]"

In this example, we create a Hash type named user and set three fields, namely name , age and email , and the corresponding values ​​are John , 30 and [email protected] respectively . By using the HGETALL command, we can get all the fields and their corresponding values, use the HGET command to get the value of a single field, and use the HMGET command to get the values ​​of multiple fields.

The following is a legend of Redis Hash type:

+--------+
|   key  |
+--------+
| name   |  value
| age    |  value
| email  |  value
+--------+

In this illustration, we use the key name as the name of the Hash type. The Hash type contains multiple fields and corresponding values, and each field has a name, such as name , age , and email . The value of a field can be any type of data, such as strings, integers, lists, etc.


List List type

When we need to store sequential data, we can use the List type of Redis. Each element in the List contains a value, which can be a string, a number, etc. Each value has a corresponding index, and the index starts from 0.

The following are some commonly used commands of the List type:
1. LPUSH/RPUSH: add one or more elements to the list from the left or right

LPUSH key value1 value2      # 从左边添加两个元素到列表中
RPUSH key value3 value4      # 从右边添加两个元素到列表中

2. LPOP/RPOP: Remove and return the first element from the left or right

LPOP key       # 移除并返回左边第一个元素
RPOP key       # 移除并返回右边第一个元素

3. LINDEX: Get the element at the specified index

LINDEX key 0      # 获取索引为0的元素

4. LRANGE: Get the elements within the specified index range and return a list

LRANGE key 0 2     # 获取索引为0~2的元素

The following is an example of a List type:

# 从左边添加三个元素到列表中
LPUSH mylist "hello"
LPUSH mylist "world"
LPUSH mylist "redis"

# 获取列表长度,应该输出3
LLEN mylist

# 获取索引为0~2的元素,应该输出["redis","world","hello"]
LRANGE mylist 0 2

# 获取索引为1的元素,应该输出"world"
LINDEX mylist 1

# 从右边移除一个元素,应该输出"hello"
RPOP mylist

# 从左边移除一个元素,应该输出"redis"
LPOP mylist

# 获取列表长度,应该输出1
LLEN mylist

Collection Set type

The Set type of Redis is an unordered collection of strings. Each string is unique (that is, there are no duplicate elements in the set). The Set type supports operations such as adding, deleting, and finding elements. The following are some common operations of the Set type:

1. Add elements:

sadd key member [member ...]

示例:
sadd myset "hello"
sadd myset "world"
sadd myset "hello"  # 该元素已存在,不会重复添加

2. Delete elements

srem key member [member ...]

示例:
srem myset "hello"

3. Get the number of elements in the collection:

scard key

示例:
scard myset

4. Determine whether the element exists in the collection:

sismember key member

示例:
sismember myset "hello" # 返回 0(false)
sismember myset "world" # 返回 1(true)

5. Get all elements in the collection:

smembers key

示例“
smembers myset # 返回 ["world"]

6. Randomly get the elements in the collection

srandmember key [count]

示例:
srandmember myset # 返回 "world"
srandmember myset 2 # 返回 ["world", "hello"](元素顺序随机)

Ordered collection ZSet type

The ZSet type of Redis is an ordered collection type, which can store multiple members, and each member has a corresponding score. According to the size of the score, the members in the ZSet can be ordered from small to large or from large to small. Sort, while members are unique in ZSet and will not be repeated.

Each member in ZSet is an element of string type, and the corresponding score is a value of type float, and the score can be used to sort members. In addition to supporting the read and write operations of common collection types, ZSet also provides some special instructions, such as inserting members, deleting members, obtaining members according to the score range, etc.

Here is a sample code:

# 连接Redis
import redis
r = redis.Redis(host='127.0.0.1', port=6379, db=0)

# 将成员和分数插入ZSet中
r.zadd('myzset', {
    
    'member1': 1, 'member2': 2})

# 获取ZSet中的成员
members = r.zrange('myzset', 0, -1)

# 根据分数范围获取成员
members_with_scores = r.zrangebyscore('myzset', 1, 2, withscores=True)

# 删除成员
r.zrem('myzset', 'member1')

Here is an example legend:

+---------------------+
| ZSet                |
|---------------------|
| member1   | score=1  |
|---------------------|
| member2   | score=2  |
+---------------------+

What scenarios are the data structures of Redis suitable for?

Redis supports five different data structures corresponding to application scenarios:

  1. String (String): A string can store any type of data, such as numbers, arrays, etc. String is the most basic data type of Redis and the most commonly used data type in Redis. In Redis, it is mainly used to store serialized objects, counters, caches, etc.
  2. Hash: A hash is a collection of key-value pairs where each key is mapped to a value. The hash type is suitable for storing objects, where each item has a list of properties. For example: user information, product information, etc.
  3. List (List): List is one of the simplest data structures in Redis. List elements are stored in the order of insertion, and fast insertion and deletion operations are supported at both ends of the list. Lists can be used to store elements that need to be sorted, such as log messages, chat records, etc.
  4. Set (Set): A set is a unique, unordered collection of strings, and the elements in the set cannot be repeated. Sets support common operations such as intersection, union, and difference, and are often used for tag management.
  5. Ordered Set (Zset): An ordered set is similar to a set, except that each element in the set has a score. The score can be any floating point number, and the score is used as an ordering basis between elements. Sorted sets are often used in the context of leaderboards or scoreboards.

In short, different data structures of Redis are suitable for different data processing scenarios. They are very flexible and easy to expand. In practical applications, we need to choose a suitable data structure to store data according to actual needs, and make full use of its characteristics to improve system performance.

Guess you like

Origin blog.csdn.net/weixin_42380504/article/details/131726231