文档 AWS SDK 示例 GitHub 存储库中还有更多 S AWS DK 示例
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
使用 SDK for Rust 的 DynamoDB 示例
以下代码示例向您展示了如何使用带有 DynamoDB 的 Rust AWS 开发工具包来执行操作和实现常见场景。
操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景的上下文查看操作。
场景是向您展示如何通过在一个服务中调用多个函数或与其他 AWS 服务结合来完成特定任务的代码示例。
AWS 社区贡献就是由多个团队创建和维护的示例 AWS。要提供反馈,请使用链接存储库中提供的机制。
每个示例都包含一个指向完整源代码的链接,您可以从中找到有关如何在上下文中设置和运行代码的说明。
操作
以下代码示例演示如何使用 CreateTable
。
- 适用于 Rust 的 SDK
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 pub async fn create_table( client: &Client, table: &str, key: &str, ) -> Result<CreateTableOutput, Error> { let a_name: String = key.into(); let table_name: String = table.into(); let ad = AttributeDefinition::builder() .attribute_name(&a_name) .attribute_type(ScalarAttributeType::S) .build() .map_err(Error::BuildError)?; let ks = KeySchemaElement::builder() .attribute_name(&a_name) .key_type(KeyType::Hash) .build() .map_err(Error::BuildError)?; let pt = ProvisionedThroughput::builder() .read_capacity_units(10) .write_capacity_units(5) .build() .map_err(Error::BuildError)?; let create_table_response = client .create_table() .table_name(table_name) .key_schema(ks) .attribute_definitions(ad) .provisioned_throughput(pt) .send() .await; match create_table_response { Ok(out) => { println!("Added table {} with key {}", table, key); Ok(out) } Err(e) => { eprintln!("Got an error creating table:"); eprintln!("{}", e); Err(Error::unhandled(e)) } } }
-
有关 API 的详细信息,请参阅适用CreateTable
于 Rust 的AWS SDK API 参考。
-
以下代码示例演示如何使用 DeleteItem
。
- 适用于 Rust 的 SDK
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 pub async fn delete_item( client: &Client, table: &str, key: &str, value: &str, ) -> Result<DeleteItemOutput, Error> { match client .delete_item() .table_name(table) .key(key, AttributeValue::S(value.into())) .send() .await { Ok(out) => { println!("Deleted item from table"); Ok(out) } Err(e) => Err(Error::unhandled(e)), } }
-
有关 API 的详细信息,请参阅适用DeleteItem
于 Rust 的AWS SDK API 参考。
-
以下代码示例演示如何使用 DeleteTable
。
- 适用于 Rust 的 SDK
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 pub async fn delete_table(client: &Client, table: &str) -> Result<DeleteTableOutput, Error> { let resp = client.delete_table().table_name(table).send().await; match resp { Ok(out) => { println!("Deleted table"); Ok(out) } Err(e) => Err(Error::Unhandled(e.into())), } }
-
有关 API 的详细信息,请参阅适用DeleteTable
于 Rust 的AWS SDK API 参考。
-
以下代码示例演示如何使用 ListTables
。
- 适用于 Rust 的 SDK
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 pub async fn list_tables(client: &Client) -> Result<Vec<String>, Error> { let paginator = client.list_tables().into_paginator().items().send(); let table_names = paginator.collect::<Result<Vec<_>, _>>().await?; println!("Tables:"); for name in &table_names { println!(" {}", name); } println!("Found {} tables", table_names.len()); Ok(table_names) }
确定表是否存在。
pub async fn table_exists(client: &Client, table: &str) -> Result<bool, Error> { debug!("Checking for table: {table}"); let table_list = client.list_tables().send().await; match table_list { Ok(list) => Ok(list.table_names().contains(&table.into())), Err(e) => Err(e.into()), } }
-
有关 API 的详细信息,请参阅适用ListTables
于 Rust 的AWS SDK API 参考。
-
以下代码示例演示如何使用 PutItem
。
- 适用于 Rust 的 SDK
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 pub async fn add_item(client: &Client, item: Item, table: &String) -> Result<ItemOut, Error> { let user_av = AttributeValue::S(item.username); let type_av = AttributeValue::S(item.p_type); let age_av = AttributeValue::S(item.age); let first_av = AttributeValue::S(item.first); let last_av = AttributeValue::S(item.last); let request = client .put_item() .table_name(table) .item("username", user_av) .item("account_type", type_av) .item("age", age_av) .item("first_name", first_av) .item("last_name", last_av); println!("Executing request [{request:?}] to add item..."); let resp = request.send().await?; let attributes = resp.attributes().unwrap(); let username = attributes.get("username").cloned(); let first_name = attributes.get("first_name").cloned(); let last_name = attributes.get("last_name").cloned(); let age = attributes.get("age").cloned(); let p_type = attributes.get("p_type").cloned(); println!( "Added user {:?}, {:?} {:?}, age {:?} as {:?} user", username, first_name, last_name, age, p_type ); Ok(ItemOut { p_type, age, username, first_name, last_name, }) }
-
有关 API 的详细信息,请参阅适用PutItem
于 Rust 的AWS SDK API 参考。
-
以下代码示例演示如何使用 Query
。
- 适用于 Rust 的 SDK
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 查找指定年份制作的电影。
pub async fn movies_in_year( client: &Client, table_name: &str, year: u16, ) -> Result<Vec<Movie>, MovieError> { let results = client .query() .table_name(table_name) .key_condition_expression("#yr = :yyyy") .expression_attribute_names("#yr", "year") .expression_attribute_values(":yyyy", AttributeValue::N(year.to_string())) .send() .await?; if let Some(items) = results.items { let movies = items.iter().map(|v| v.into()).collect(); Ok(movies) } else { Ok(vec![]) } }
-
有关 API 详细信息,请参阅《AWS SDK for Rust API 参考》中的 Query
。
-
以下代码示例演示如何使用 Scan
。
- 适用于 Rust 的 SDK
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 pub async fn list_items(client: &Client, table: &str, page_size: Option<i32>) -> Result<(), Error> { let page_size = page_size.unwrap_or(10); let items: Result<Vec<_>, _> = client .scan() .table_name(table) .limit(page_size) .into_paginator() .items() .send() .collect() .await; println!("Items in table (up to {page_size}):"); for item in items? { println!(" {:?}", item); } Ok(()) }
-
有关 API 详细信息,请参阅《AWS SDK for Rust API 参考》中的 Scan
。
-
场景
以下代码示例演示如何覆盖终端节点 URL 以连接到 DynamoDB 和软件开发工具包的本地开发部署。 AWS
有关更多信息,请参阅 DynamoDB Local。
- 适用于 Rust 的 SDK
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 /// Lists your tables from a local DynamoDB instance by setting the SDK Config's /// endpoint_url and test_credentials. #[tokio::main] async fn main() { tracing_subscriber::fmt::init(); let config = aws_config::defaults(aws_config::BehaviorVersion::latest()) .test_credentials() // DynamoDB run locally uses port 8000 by default. .endpoint_url("http://localhost:8000") .load() .await; let dynamodb_local_config = aws_sdk_dynamodb::config::Builder::from(&config).build(); let client = aws_sdk_dynamodb::Client::from_conf(dynamodb_local_config); let list_resp = client.list_tables().send().await; match list_resp { Ok(resp) => { println!("Found {} tables", resp.table_names().len()); for name in resp.table_names() { println!(" {}", name); } } Err(err) => eprintln!("Failed to list local dynamodb tables: {err:?}"), } }
以下代码示例演示如何创建无服务器应用程序,让用户能够使用标签管理照片。
以下代码示例展示了如何:
通过运行 SELECT 语句来获取项目。
通过运行 INSERT 语句来添加项目。
通过运行 UPDATE 语句来更新项目。
通过运行 DELETE 语句来删除项目。
- 适用于 Rust 的 SDK
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 async fn make_table( client: &Client, table: &str, key: &str, ) -> Result<(), SdkError<CreateTableError>> { let ad = AttributeDefinition::builder() .attribute_name(key) .attribute_type(ScalarAttributeType::S) .build() .expect("creating AttributeDefinition"); let ks = KeySchemaElement::builder() .attribute_name(key) .key_type(KeyType::Hash) .build() .expect("creating KeySchemaElement"); let pt = ProvisionedThroughput::builder() .read_capacity_units(10) .write_capacity_units(5) .build() .expect("creating ProvisionedThroughput"); match client .create_table() .table_name(table) .key_schema(ks) .attribute_definitions(ad) .provisioned_throughput(pt) .send() .await { Ok(_) => Ok(()), Err(e) => Err(e), } } async fn add_item(client: &Client, item: Item) -> Result<(), SdkError<ExecuteStatementError>> { match client .execute_statement() .statement(format!( r#"INSERT INTO "{}" VALUE {{ "{}": ?, "acount_type": ?, "age": ?, "first_name": ?, "last_name": ? }} "#, item.table, item.key )) .set_parameters(Some(vec![ AttributeValue::S(item.utype), AttributeValue::S(item.age), AttributeValue::S(item.first_name), AttributeValue::S(item.last_name), ])) .send() .await { Ok(_) => Ok(()), Err(e) => Err(e), } } async fn query_item(client: &Client, item: Item) -> bool { match client .execute_statement() .statement(format!( r#"SELECT * FROM "{}" WHERE "{}" = ?"#, item.table, item.key )) .set_parameters(Some(vec![AttributeValue::S(item.value)])) .send() .await { Ok(resp) => { if !resp.items().is_empty() { println!("Found a matching entry in the table:"); println!("{:?}", resp.items.unwrap_or_default().pop()); true } else { println!("Did not find a match."); false } } Err(e) => { println!("Got an error querying table:"); println!("{}", e); process::exit(1); } } } async fn remove_item(client: &Client, table: &str, key: &str, value: String) -> Result<(), Error> { client .execute_statement() .statement(format!(r#"DELETE FROM "{table}" WHERE "{key}" = ?"#)) .set_parameters(Some(vec![AttributeValue::S(value)])) .send() .await?; println!("Deleted item."); Ok(()) } async fn remove_table(client: &Client, table: &str) -> Result<(), Error> { client.delete_table().table_name(table).send().await?; Ok(()) }
-
有关 API 的详细信息,请参阅适用ExecuteStatement
于 Rust 的AWS SDK API 参考。
-
以下代码示例展示了如何:
从 JPG、JPEG 或 PNG 文件中获取 EXIF 信息。
将图像文件上传到 Amazon S3 存储桶。
使用 Amazon Rekognition 识别文件中的三个主要属性(标签)。
将 EXIF 和标签信息添加到该区域的 Amazon DynamoDB 表中。
- 适用于 Rust 的 SDK
-
从 JPG、JPEG 或 PNG 文件中获取 EXIF 信息,将图像文件上传到 Amazon S3 存储桶,使用 Amazon Rekognition 识别文件中的三个主要属性(Amazon Rekognition 中的标签),然后将 EXIF 和标签信息添加到该区域的 Amazon DynamoDB 表中。
有关如何设置和运行的完整源代码和说明,请参阅上的完整示例GitHub
。 本示例中使用的服务
DynamoDB
Amazon Rekognition
Amazon S3
无服务器示例
以下代码示例演示如何实现 Lambda 函数,该函数接收通过从 DynamoDB 流接收记录而触发的事件。该函数检索 DynamoDB 有效负载,并记录下记录内容。
- 适用于 Rust 的 SDK
-
注意
还有更多相关信息 GitHub。在无服务器示例
存储库中查找完整示例,并了解如何进行设置和运行。 使用 Rust 将 DynamoDB 事件与 Lambda 结合使用。
use lambda_runtime::{service_fn, tracing, Error, LambdaEvent}; use aws_lambda_events::{ event::dynamodb::{Event, EventRecord}, }; // Built with the following dependencies: //lambda_runtime = "0.11.1" //serde_json = "1.0" //tokio = { version = "1", features = ["macros"] } //tracing = { version = "0.1", features = ["log"] } //tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt"] } //aws_lambda_events = "0.15.0" async fn function_handler(event: LambdaEvent<Event>) ->Result<(), Error> { let records = &event.payload.records; tracing::info!("event payload: {:?}",records); if records.is_empty() { tracing::info!("No records found. Exiting."); return Ok(()); } for record in records{ log_dynamo_dbrecord(record); } tracing::info!("Dynamo db records processed"); // Prepare the response Ok(()) } fn log_dynamo_dbrecord(record: &EventRecord)-> Result<(), Error>{ tracing::info!("EventId: {}", record.event_id); tracing::info!("EventName: {}", record.event_name); tracing::info!("DynamoDB Record: {:?}", record.change ); Ok(()) } #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .with_target(false) .without_time() .init(); let func = service_fn(function_handler); lambda_runtime::run(func).await?; Ok(()) }
以下代码示例演示如何为接收来自 DynamoDB 流的事件的 Lambda 函数实现部分批量响应。该函数在响应中报告批处理项目失败,并指示 Lambda 稍后重试这些消息。
- 适用于 Rust 的 SDK
-
注意
还有更多相关信息 GitHub。在无服务器示例
存储库中查找完整示例,并了解如何进行设置和运行。 报告使用 Rust 通过 Lambda 进行 DynamoDB 批处理项目失败。
use aws_lambda_events::{ event::dynamodb::{Event, EventRecord, StreamRecord}, streams::{DynamoDbBatchItemFailure, DynamoDbEventResponse}, }; use lambda_runtime::{run, service_fn, Error, LambdaEvent}; /// Process the stream record fn process_record(record: &EventRecord) -> Result<(), Error> { let stream_record: &StreamRecord = &record.change; // process your stream record here... tracing::info!("Data: {:?}", stream_record); Ok(()) } /// Main Lambda handler here... async fn function_handler(event: LambdaEvent<Event>) -> Result<DynamoDbEventResponse, Error> { let mut response = DynamoDbEventResponse { batch_item_failures: vec![], }; let records = &event.payload.records; if records.is_empty() { tracing::info!("No records found. Exiting."); return Ok(response); } for record in records { tracing::info!("EventId: {}", record.event_id); // Couldn't find a sequence number if record.change.sequence_number.is_none() { response.batch_item_failures.push(DynamoDbBatchItemFailure { item_identifier: Some("".to_string()), }); return Ok(response); } // Process your record here... if process_record(record).is_err() { response.batch_item_failures.push(DynamoDbBatchItemFailure { item_identifier: record.change.sequence_number.clone(), }); /* Since we are working with streams, we can return the failed item immediately. Lambda will immediately begin to retry processing from this failed item onwards. */ return Ok(response); } } tracing::info!("Successfully processed {} record(s)", records.len()); Ok(response) } #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) // disable printing the name of the module in every log line. .with_target(false) // disabling time is handy because CloudWatch will add the ingestion time. .without_time() .init(); run(service_fn(function_handler)).await }
AWS 社区捐款
以下代码示例展示了如何使用带有 Lambda 和 DynamoDB 的 API Gateway 来构建和测试无服务器应用程序
- 适用于 Rust 的 SDK
-
演示如何使用 Rust SDK 构建和测试包含 API Gateway 以及 Lambda 和 DynamoDB 的无服务器应用程序。
有关如何设置和运行的完整源代码和说明,请参阅上的完整示例GitHub
。 本示例中使用的服务
API Gateway
DynamoDB
Lambda