AWS SDK を使用して DynamoDB テーブルを一覧表示する - AWSSDK コードサンプル

AWSDocAWS SDKGitHub サンプルリポジトリには、さらに多くの SDK サンプルがあります

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

AWS SDK を使用して DynamoDB テーブルを一覧表示する

次のコード例は、DynamoDB テーブルを一覧表示する方法を示しています。

.NET
AWS SDK for .NET
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

private static async Task ListMyTables() { Console.WriteLine("\n*** Listing tables ***"); string? lastTableNameEvaluated = null; do { var response = await Client.ListTablesAsync(new ListTablesRequest { Limit = 2, ExclusiveStartTableName = lastTableNameEvaluated }); foreach (var name in response.TableNames) { Console.WriteLine(name); } lastTableNameEvaluated = response.LastEvaluatedTableName; } while (lastTableNameEvaluated != null); }
  • API の詳細については、AWS SDK for .NETAPI ListTablesリファレンスのを参照してください

C++
SDK for C++
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

//! List the Amazon DynamoDB tables for the current AWS account. /*! \sa listTables() \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::DynamoDB::listTables( const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration); Aws::DynamoDB::Model::ListTablesRequest listTablesRequest; listTablesRequest.SetLimit(50); do { const Aws::DynamoDB::Model::ListTablesOutcome &outcome = dynamoClient.ListTables( listTablesRequest); if (!outcome.IsSuccess()) { std::cout << "Error: " << outcome.GetError().GetMessage() << std::endl; return false; } for (const auto &tableName: outcome.GetResult().GetTableNames()) std::cout << tableName << std::endl; listTablesRequest.SetExclusiveStartTableName( outcome.GetResult().GetLastEvaluatedTableName()); } while (!listTablesRequest.GetExclusiveStartTableName().empty()); return true; }
  • API の詳細については、AWS SDK for C++API ListTablesリファレンスのを参照してください

Go
SDK for Go V2
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples. // It contains a DynamoDB service client that is used to act on the specified table. type TableBasics struct { DynamoDbClient *dynamodb.Client TableName string } // ListTables lists the DynamoDB table names for the current account. func (basics TableBasics) ListTables() ([]string, error) { var tableNames []string tables, err := basics.DynamoDbClient.ListTables( context.TODO(), &dynamodb.ListTablesInput{}) if err != nil { log.Printf("Couldn't list tables. Here's why: %v\n", err) } else { tableNames = tables.TableNames } return tableNames, err }
  • API の詳細については、AWS SDK for GoAPI ListTablesリファレンスのを参照してください

Java
SDK for Java 2.x
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

public static void listAllTables(DynamoDbClient ddb){ boolean moreTables = true; String lastName = null; while(moreTables) { try { ListTablesResponse response = null; if (lastName == null) { ListTablesRequest request = ListTablesRequest.builder().build(); response = ddb.listTables(request); } else { ListTablesRequest request = ListTablesRequest.builder() .exclusiveStartTableName(lastName).build(); response = ddb.listTables(request); } List<String> tableNames = response.tableNames(); if (tableNames.size() > 0) { for (String curName : tableNames) { System.out.format("* %s\n", curName); } } else { System.out.println("No tables found!"); System.exit(0); } lastName = response.lastEvaluatedTableName(); if (lastName == null) { moreTables = false; } } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } System.out.println("\nDone!"); }
  • API の詳細については、AWS SDK for Java 2.xAPI ListTablesリファレンスのを参照してください

JavaScript
SDK for forJavaScript (v3)
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

クライアントを作成します。

// Create service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon DynamoDB service client object. const ddbClient = new DynamoDBClient({ region: REGION }); export { ddbClient };

テーブルを一覧表示します。

// Import required AWS SDK clients and commands for Node.js import { ListTablesCommand } from "@aws-sdk/client-dynamodb"; import { ddbClient } from "./libs/ddbClient.js"; export const run = async () => { try { const data = await ddbClient.send(new ListTablesCommand({})); console.log(data); // console.log(data.TableNames.join("\n")); return data; } catch (err) { console.error(err); } }; run();
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、AWS SDK for JavaScriptAPI ListTablesリファレンスのを参照してください

SDK for forJavaScript (v2)
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); // Call DynamoDB to retrieve the list of tables ddb.listTables({Limit: 10}, function(err, data) { if (err) { console.log("Error", err.code); } else { console.log("Table names are ", data.TableNames); } });
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、AWS SDK for JavaScriptAPI ListTablesリファレンスのを参照してください

Kotlin
SDK for Kotlin
注記

これはプレビューリリースの機能に関するプレリリースドキュメントです。このドキュメントは変更される可能性があります。

注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

suspend fun listAllTables() { DynamoDbClient { region = "us-east-1" }.use { ddb -> val response = ddb.listTables(ListTablesRequest {}) response.tableNames?.forEach { tableName -> println("Table name is $tableName") } } }
  • API の詳細については、「AWSSDK for Kotlin API リファレンス」を参照してくださいListTables

PHP
SDK for PHP
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

public function listTables($exclusiveStartTableName = "", $limit = 100) { $this->dynamoDbClient->listTables([ 'ExclusiveStartTableName' => $exclusiveStartTableName, 'Limit' => $limit, ]); }
  • API の詳細については、AWS SDK for PHPAPI ListTablesリファレンスのを参照してください

Python
SDK for Python (Boto3)
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

class Movies: """Encapsulates an Amazon DynamoDB table of movie data.""" def __init__(self, dyn_resource): """ :param dyn_resource: A Boto3 DynamoDB resource. """ self.dyn_resource = dyn_resource self.table = None def list_tables(self): """ Lists the Amazon DynamoDB tables for the current account. :return: The list of tables. """ try: tables = [] for table in self.dyn_resource.tables.all(): print(table.name) tables.append(table) except ClientError as err: logger.error( "Couldn't list tables. Here's why: %s: %s", err.response['Error']['Code'], err.response['Error']['Message']) raise else: return tables
  • API の詳細については、「AWSSDK for Python (Boto3) API リファレンス」のを参照してくださいListTables

Ruby
SDK for Ruby
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

テーブルが存在するかどうかを確認します。

# Encapsulates an Amazon DynamoDB table of movie data. class Scaffold attr_reader :dynamo_resource attr_reader :table_name attr_reader :table def initialize(table_name) client = Aws::DynamoDB::Client.new(region: "us-east-1") @dynamo_resource = Aws::DynamoDB::Resource.new(client: client) @table_name = table_name @table = nil @logger = Logger.new($stdout) @logger.level = Logger::DEBUG end # Determines whether a table exists. As a side effect, stores the table in # a member variable. # # @param table_name [String] The name of the table to check. # @return [Boolean] True when the table exists; otherwise, False. def exists?(table_name) @dynamo_resource.client.describe_table(table_name: table_name) @logger.debug("Table #{table_name} exists") rescue Aws::DynamoDB::Errors::ResourceNotFoundException @logger.debug("Table #{table_name} doesn't exist") false rescue Aws::DynamoDB::Errors::ServiceError => e puts("Couldn't check for existence of #{table_name}:\n") puts("\t#{e.code}: #{e.message}") raise end
  • API の詳細については、AWS SDK for RubyAPI ListTablesリファレンスのを参照してください

Rust
SDK for Rust
注記

これはプレビューリリースの SDK に関するドキュメントです。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().as_ref().unwrap().contains(&table.into())), Err(e) => Err(e.into()), } }
  • API の詳細については、「AWSSDK for Rust API リファレンス」を参照してくださいListTables

Swift
SDK for Swift
注記

これはプレビューリリースの SDK に関するプレリリースドキュメントです。このドキュメントは変更される可能性があります。

注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

/// Get a list of the DynamoDB tables available in the specified Region. /// /// - Returns: An array of strings listing all of the tables available /// in the Region specified when the session was created. public func getTableList() async throws -> [String] { var tableList: [String] = [] var lastEvaluated: String? = nil // Iterate over the list of tables, 25 at a time, until we have the // names of every table. Add each group to the `tableList` array. // Iteration is complete when `output.lastEvaluatedTableName` is `nil`. repeat { let input = ListTablesInput( exclusiveStartTableName: lastEvaluated, limit: 25 ) let output = try await self.session.listTables(input: input) guard let tableNames = output.tableNames else { return tableList } tableList.append(contentsOf: tableNames) lastEvaluated = output.lastEvaluatedTableName } while lastEvaluated != nil return tableList }
  • API の詳細については、AWSSDK for Swift API リファレンスの「発行」を参照してくださいListTables