如何在Rust中为DynamoDB定义复合主键?
在Rust中为DynamoDB定义复合主键的方法
在Rust的AWS SDK中,要定义DynamoDB的复合主键,关键是多次调用key_schema方法,每次传入一个KeySchemaElement对象——分别对应分区键(HASH)和排序键(RANGE)。和Python/JS直接传字典数组不同,Rust通过链式调用逐个添加主键元素。
完整代码示例
use aws_sdk_dynamodb::model::{ AttributeDefinition, KeySchemaElement, KeyType, ProvisionedThroughput, ScalarAttributeType, }; use aws_sdk_dynamodb::Client; async fn create_table_with_composite_key(client: &Client, table_name: &str) { // 1. 定义主键结构:分区键(user_id)+ 排序键(order_id) let partition_key = KeySchemaElement::builder() .attribute_name("user_id") .key_type(KeyType::Hash) .build() .unwrap(); let sort_key = KeySchemaElement::builder() .attribute_name("order_id") .key_type(KeyType::Range) .build() .unwrap(); // 2. 声明主键的属性类型 let attribute_definitions = vec![ AttributeDefinition::builder() .attribute_name("user_id") .attribute_type(ScalarAttributeType::S) // 字符串类型 .build() .unwrap(), AttributeDefinition::builder() .attribute_name("order_id") .attribute_type(ScalarAttributeType::N) // 数字类型 .build() .unwrap(), ]; // 3. 设置吞吐量(按需模式可省略此步骤) let provisioned_throughput = ProvisionedThroughput::builder() .read_capacity_units(5) .write_capacity_units(5) .build() .unwrap(); // 4. 创建表 match client .create_table() .table_name(table_name) .key_schema(partition_key) // 添加分区键 .key_schema(sort_key) // 添加排序键 .attribute_definitions(attribute_definitions) .provisioned_throughput(provisioned_throughput) .send() .await { Ok(_) => println!("表 {} 创建成功,复合主键为 (user_id, order_id)", table_name), Err(e) => { eprintln!("创建表时出错:{}", e); } }; }
关键说明
key_schema链式调用:每次调用都会向主键列表中添加一个元素,先传分区键、再传排序键即可组成复合主键。AttributeDefinition的必要性:必须为每个主键字段声明数据类型(比如ScalarAttributeType::S代表字符串,N代表数字),且名称要和KeySchemaElement中的完全一致。- 吞吐量设置:如果使用按需计费模式,可以移除
provisioned_throughput相关代码,改用billing_mode(BillingMode::PayPerRequest)。
内容的提问来源于stack exchange,提问作者Terry Jung
相关产品推荐
相关产品推荐

