如何用PynamoDB实现DynamoDB基于订单状态与日期范围的查询
当然可以用PynamoDB实现这个查询!
不过先得修正你定义的模型里的一个关键问题,然后就能轻松完成需求了。
首先修正模型定义
你在Order类里同时把order_id和order_status都标记为hash_key=True,这不符合DynamoDB的规则——一张表只能有一个主键(要么是单独的hash key,要么是hash+range的复合主键)。order_status应该作为普通属性存在,因为你已经在全局二级索引(GSI)OrderStatusIndex里把它设为了索引的hash key。修正后的模型如下:
from pynamodb.models import Model from pynamodb.attributes import NumberAttribute, UnicodeAttribute from pynamodb.indexes import GlobalSecondaryIndex, AllProjection class OrderStatusIndex(GlobalSecondaryIndex): class Meta: index_name = 'OrderStatusIndex' read_capacity_units = 2 write_capacity_units = 1 projection = AllProjection() order_status = NumberAttribute(hash_key=True) created_on = UnicodeAttribute(range_key=True) class Order(Model): class Meta: table_name = 'order' host = 'http://localhost:8000' read_capacity_units = 2 write_capacity_units = 1 # 表的主键:order_id作为hash key,created_on作为range key(可根据实际需求调整) order_id = NumberAttribute(hash_key=True) # 修正:order_status改为普通属性,不再是表的主键 order_status = NumberAttribute() created_on = UnicodeAttribute(range_key=True) order_status_index = OrderStatusIndex()
执行目标查询
修正模型后,你就可以通过OrderStatusIndex这个GSI来执行和MySQL语句等价的查询了。PynamoDB的GSI提供了query方法,正好匹配你的需求:
- 用
hash_key指定order_status = 0 - 用
range_key_condition来筛选created_on的日期范围
示例代码如下:
# 假设你的日期格式是字符串,比如'2024-01-01'、'2024-01-31' start_date = '2024-01-01' end_date = '2024-01-31' # 通过GSI执行查询 results = Order.order_status_index.query( hash_key=0, range_key_condition=Order.created_on.between(start_date, end_date) ) # 遍历查询结果 for order in results: print(f"订单ID: {order.order_id}, 状态: {order.order_status}, 创建时间: {order.created_on}")
为什么这样可行?
你的GSIOrderStatusIndex的结构完美匹配查询条件:
- hash key:
order_status(对应MySQL查询里的order_status = 0) - range key:
created_on(对应MySQL里的created_on >= start_date and created_on <= end_date)
DynamoDB可以高效地通过GSI定位到符合条件的条目,和你想要的MySQL查询逻辑完全一致。
内容的提问来源于stack exchange,提问作者themindFuel
相关产品推荐
相关产品推荐

