SDK for Rust を使用した DynamoDB の例 - AWS SDK コード例

Doc AWS SDK Examples GitHub リポジトリには、他にも SDK の例があります。 AWS

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

SDK for Rust を使用した DynamoDB の例

次のコード例は、DynamoDB で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

アクションはより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

「シナリオ」は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

AWS コミュニティへの貢献は、複数のチームが作成し、維持している例です AWS。フィードバックを提供するには、リンクされたリポジトリで提供されているメカニズムを使用します。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

アクション

次のコード例は、CreateTable を使用する方法を示しています。

SDK for Rust
注記

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 の詳細については、「AWS SDK for Rust API リファレンス」の「CreateTable」を参照してください。

次の例は、DeleteItem を使用する方法を説明しています。

SDK for Rust
注記

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 の詳細については、「AWS SDK for Rust API リファレンス」の「DeleteItem」を参照してください。

次の例は、DeleteTable を使用する方法を説明しています。

SDK for Rust
注記

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 の詳細については、「AWS SDK for Rust API リファレンス」の「DeleteTable」を参照してください。

次の例は、ListTables を使用する方法を説明しています。

SDK for Rust
注記

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 の詳細については、「AWS SDK for Rust API リファレンス」の「ListTables」を参照してください。

次の例は、PutItem を使用する方法を説明しています。

SDK for Rust
注記

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 の詳細については、「AWS SDK for Rust API リファレンス」の「PutItem」を参照してください。

次のコード例は、Query を使用する方法を示しています。

SDK for Rust
注記

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 を使用する方法を説明しています。

SDK for Rust
注記

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 SDK のローカル開発デプロイに接続する方法を示しています。

詳細については、「DynamoDB Local」を参照してください。

SDK for Rust
注記

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:?}"), } }

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

SDK for Rust

Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。

完全なソースコードと設定および実行の手順については、GitHub で完全な例を参照してください。

この例のソースについて詳しくは、AWS  コミュニティでブログ投稿を参照してください。

この例で使用されているサービス
  • API Gateway

  • DynamoDB

  • Lambda

  • Amazon Rekognition

  • Amazon S3

  • Amazon SNS

次のコードサンプルは、以下の操作方法を示しています。

  • SELECT ステートメントを実行して項目を取得する。

  • INSERT 文を実行して項目を追加する。

  • UPDATE ステートメントを使用して項目を更新する。

  • DELETE ステートメントを実行して項目を削除する。

SDK for Rust
注記

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 の詳細については、「AWS SDK for Rust API リファレンス」の「ExecuteStatement」を参照してください。

次のコードサンプルは、以下の操作方法を示しています。

  • JPG、JPEG、または PNG ファイルから EXIF 情報を取得します。

  • Amazon S3 バケットにイメージファイルをアップロードします。

  • Amazon Rekognition を使用して、ファイル内の 3 つの上位属性 (ラベル) を特定します。

  • EXIF およびラベル情報を、リージョンの Amazon DynamoDB テーブルに追加します。

SDK for Rust

JPG、JPEG、または PNG ファイルから EXIF 情報を取得し、イメージファイルを Amazon S3 バケットにアップロードし、Amazon Rekognition を使用してファイル内の 3 つの上位属性 (Amazon Rekognition のラベル) を特定し、リージョンの Amazon DynamoDB テーブルに EXIF およびラベル情報を追加します。

完全なソースコードとセットアップおよび実行の手順については、GitHub で完全な例を参照してください。

この例で使用されているサービス
  • DynamoDB

  • Amazon Rekognition

  • Amazon S3

サーバーレスサンプル

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受信する Lambda 関数を実装する方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

SDK for Rust
注記

GitHub には、その他のリソースもあります。サーバーレスサンプルリポジトリで完全な例を検索し、設定および実行の方法を確認してください。

Rust を使用して Lambda で DynamoDB イベントを利用します。

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 に伝えます。

SDK for Rust
注記

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 を使用してサーバーレスアプリケーションを構築およびテストする方法を示しています。

SDK for Rust

Rust SDK を使用し、Lambda および DynamoDB を備えた API Gateway で構成されるサーバーレスアプリケーションを構築およびテストする方法が示されます。

完全なソースコードとセットアップおよび実行の手順については、GitHub で完全な例を参照してください。

この例で使用されているサービス
  • API Gateway

  • DynamoDB

  • Lambda