Home >Database >Redis >Let's talk about the hash data type in redis and how to operate it?

Let's talk about the hash data type in redis and how to operate it?

青灯夜游
青灯夜游forward
2021-12-31 10:16:252596browse

This article will take you to understand the hash data type in redis and introduce the basic operations of hash type data. I hope it will be helpful to everyone!

Let's talk about the hash data type in redis and how to operate it?

1. Overview of hash type data

Let’s look at this example first

In the previous section we Let’s learn about the string storage type together. However, if the storage of object data has frequent update requirements, the operation will be cumbersome. For example: user:id:100 -> {"id":100,"name":"Spring Festival Gala","fans":12355,"blogs":99,"focus:83}, if If you need to update local data in an object, you need to replace all the data, so you have the following requirements. [Related recommendations: Redis Video Tutorial]

New requirements: Group a series of stored data to facilitate management, such as storing information about an object Required storage structure : One storage space stores multiple key-value pair data

as shown below :

Lets talk about the hash data type in redis and how to operate it?

In order to solve this problem, we introduce a new data type: hash. At the same time, the hash storage structure has also been optimized as follows

  • If the number of fields is small, the storage structure is optimized to be an array-like structure
  • If the number of fields is large, the storage structure uses the HashMap structure

2. Basics of hash type data Operation

  • Modify/add data
hset key field value
  • Query a single field/Query all fields
# 查询单个字段数据
hget key field
# 查询所有数据
hgetall key
  • Delete operation
hdel key field1 [field2]
  • Modify/add multiple data
hmset key field1 value1 field2 value2
  • Return the value of one or more given fields in the hash table
hmget key field1 field2
  • Get the number of fields in the hash table
hlen key
  • Get whether the specified field exists in the hash table
hexists key field

3. hash Extended operations for type data

  • Get all field names or field values ​​in the hash table
hkey key
hvals key
  • Set the numerical data of the specified character segment and increase the value of the specified range
hincrby key field increment
hincrbyfloat key field increment

Hash type data operation precautions

  • The value under the hash type can only store strings, other data types are not allowed to be stored, and there are no nested objects. .If the data is not obtained, the corresponding result is (nil);

  • Each hash can store 2 to the 32nd power minus 1 key-value pair;

  • The hash type is very close to the data storage form of the object, and can flexibly add and delete object attributes. However, the original intention of the hash design is not to store a large number of objects. Remember not to abuse it, let alone use the hash as an object list;

  • hgetall operation can obtain all attributes. If there are too many internal fields, traversing the entire data will be inefficient and may become a data access bottleneck.

4. Application cases of hash

4.1. Using hash to implement shopping cart

Overview

Here we do not discuss the persistent synchronization between the shopping cart and the database, nor the relationship between the shopping cart and the order, and ignore the storage of shopping cart information for non-logged-in users. We only use the redis storage model to add, browse, change quantity, delete, and clear items in the shopping cart

Implementation plan

  • Using the customer ID as the key, each user creates a hash storage structure corresponding to the shopping cart information
  • Using the product number as the field and the purchase quantity as the value for storage
  • Add product: add new Field and value
  • Browse products: traverse hash
  • Change quantity: auto-increment/auto-decrement, set value
  • Delete product: delete field
  • Clear: Delete key

The sample code is as follows:

# 001 用户购买 ID为101商品 100件,ID为102的商品 200件
hmset 001 101 100 102 200
# 002 用户购买 ID为102商品 1件,ID为104的商品 7件
hmset 002 102 1 104 7

Product information acceleration

Currently only the quantity is stored in redis, and It does not speed up the process because the product information still needs to be queried in the database. The following solution can be used:

The product information record in each shopping cart is saved as two fields

  • field1 is specially used to save the quantity

Naming format: product id:nums Save data: Value

  • field2 is specially used to save the product information displayed in the shopping cart, including text description, picture address, affiliated business information, etc.

Naming format: Product id:info Save data: json

The sample code is as follows:

# 001 用户 购买 ID为101的商品 2件,商品的信息为:{"name":"good name"} 
hmset 001 101:num 2  101:info "{\"name\":\"goods name\"}"
# 002 用户 购买 ID为101的商品 1件,商品的信息为:{"name":"good name"} 
hmset 002 101:num 1  101:info "{\"name\":\"goods name\"}"

In the value corresponding to 101:info above, the string contains spaces, so it is quoted with double quotes , to achieve the purpose of escaping.

Product information is saved independently

Since field2 may exist in multiple product records, the data in field2 can be saved in an independent hash. At this time, it is obviously unreasonable to save the hash data every time a shopping cart record is added. You can save the data through the hsetnx operation. If the data exists, the save operation will not be performed.

The command format is as follows

hsetnx key field value

The code example is as follows

# 将id为101 的商品独立存起来
hsetnx info 101 "{\"name\":\"goods name\"}"

4.1. 用hash实现抢购

案例:双 11 活动日,销售手机充值卡的商家对移动、联通、电信的 30 元、50 元、100 元商品推出抢购活动,每种商品的抢购上限为 100。

解决方案

  • 以商家 id 作为 key
  • 将参与抢购的商品作为 field
  • 将参与抢购的商品数量作为对应的 value
  • 抢购时使用降值的方式控制产品数量
  • 实际业务中还有超卖等实际问题,这里不做讨论

实现过程

商品初始信息

# p01商家下,c30充值券1000张,c50充值券1000张,c100充值券1000张
hmset p01 c30 1000 c50 1000 c100 1000

当 c30 售出1件时,值减 1; 当 c100 售出 20 件时,值减 20,如下代码

# p01商家,商品c30售出1件
hincrby p01 c30 -1
# p01商家,商品c100售出20件
hincrby p01 c100 -20

5. string 存对象对比 hash 存对象

  • string 存储 json 字符串:读取方便,在更新的时候会整体进行更新

  • hash 存对象具体的字段:更新灵活

引入 hash 数据类型之后,我们就解决了 string 存储对象,更新对象时需要整体更新的问题。

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Let's talk about the hash data type in redis and how to operate it?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete