0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Rust】AWS LambdaでDynamoDB検索

Last updated at Posted at 2022-04-09

AWS LambdaをRustで実装する際のサンプルコードが少なすぎるのでメモ

内容

DynamoDBの検索(スキャン)
例として、とある学校の生徒管理テーブルから指定した部活に所属する生徒の氏名一覧で取得することを考える。

  • テーブル名:students_table
    • 項目1:name(氏名)
    • 項目2:club(部活)

コード

Cargo.toml
[package]
name = "sample"
version = "0.1.0"
edition = "2021"

[dependencies]
aws-config = "0.9.0"
aws-types = "0.9.0"
aws-sdk-dynamodb = "0.9.0"
lambda_runtime = "0.5.1"
serde_json = "1.0.79"
tokio = "1.17.0"
main.rs
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_dynamodb::model::AttributeValue;
use aws_sdk_dynamodb::Client as DdbClient;
use aws_types::region::Region;
use lambda_runtime::{service_fn, Error, LambdaEvent};
use serde_json::{json, Value};
use std::process::exit;

#[tokio::main]
async fn main() -> Result<(), Error> {
    let func = service_fn(func);
    lambda_runtime::run(func).await?;
    Ok(())
}

async fn func(_event: LambdaEvent<Value>) -> Result<Value, Error> {
    // DynamoDBクライアント用意
    let region_provider = RegionProviderChain::first_try(Region::new("ap-northeast-1"));
    let shared_config = aws_config::from_env().region(region_provider).load().await;
    let client = DdbClient::new(&shared_config);

    // 検索
    let club = "baseball"; // 検索対象(野球部)
    let names = match client
        .scan()
        .table_name("students_table")
        .filter_expression(format!("club = :val"))
        .expression_attribute_values(":val", AttributeValue::S(club.into()))
        .send()
        .await
    {
        Ok(output) => {
            println!("Found {} items from DynamoDB", output.count());
            let mut names: Vec<String> = Vec::new();
            // 検索結果一覧取得
            let items = output.items().unwrap();
            // name取り出し
            for item in items {
                names.push(item["name"].as_s().unwrap().clone());
            }
            names
        }
        Err(e) => {
            println!("Got an error while scanning DB: {}", e);
            exit(1);
        }
    };

    // 検索結果を表示
    for name in names {
        println!("{}", name)
    }

    Ok(json!({ "message": "success" }))
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?