SDK를 사용하여 DynamoDB 테이블 나열 AWS - Amazon DynamoDB

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

SDK를 사용하여 DynamoDB 테이블 나열 AWS

다음 코드 예제에서는 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 .NET API ListTables참조를 참조하십시오.

Bash
AWS CLI Bash 스크립트 사용
참고

더 많은 정보가 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

############################################################################## # function dynamodb_list_tables # # This function lists all the tables in a DynamoDB. # # Returns: # 0 - If successful. # 1 - If it fails. ########################################################################### function dynamodb_list_tables() { response=$(aws dynamodb list-tables \ --output text \ --query "TableNames") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports batch-write-item operation failed.$response" return 1 fi echo "$response" | tr -s "[:space:]" "\n" return 0 }

이 예제에 사용된 유틸리티 함수

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • API 세부 정보는 AWS CLI 명령 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참조를 참조하십시오.

CLI
AWS CLI

예 1: 테이블을 나열하는 방법

다음 list-tables 예시는 현재 AWS 계정 및 지역과 관련된 모든 테이블을 나열합니다.

aws dynamodb list-tables

출력:

{ "TableNames": [ "Forum", "ProductCatalog", "Reply", "Thread" ] }

자세한 내용은 Amazon DynamoDB 개발자 안내서의 테이블 이름 나열을 참조하세요.

예 2: 페이지 크기를 제한하는 방법

다음 예시에서는 모든 기존 테이블의 목록을 반환하지만 각 호출에서 항목을 하나만 검색하고, 필요한 경우 전체 목록을 가져오기 위해 여러 번 호출합니다. 페이지 크기 제한은 많은 리소스에서 list 명령을 실행할 때 유용합니다. 리소스가 많을 때 기본 페이지 크기인 1,000을 사용하면 '시간 초과' 오류가 발생할 수 있습니다.

aws dynamodb list-tables \ --page-size 1

출력:

{ "TableNames": [ "Forum", "ProductCatalog", "Reply", "Thread" ] }

자세한 내용은 Amazon DynamoDB 개발자 안내서의 테이블 이름 나열을 참조하세요.

예 3: 반환되는 항목 수를 제한하는 방법

다음 예시에서는 반환되는 항목 수를 2개로 제한합니다. 응답에는 결과의 다음 페이지를 검색하는 데 사용되는 NextToken 값이 포함됩니다.

aws dynamodb list-tables \ --max-items 2

출력:

{ "TableNames": [ "Forum", "ProductCatalog" ], "NextToken": "abCDeFGhiJKlmnOPqrSTuvwxYZ1aBCdEFghijK7LM51nOpqRSTuv3WxY3ZabC5dEFGhI2Jk3LmnoPQ6RST9" }

자세한 내용은 Amazon DynamoDB 개발자 안내서의 테이블 이름 나열을 참조하세요.

예 4: 결과의 다음 페이지를 검색하는 방법

다음 명령은 이전의 list-tables 명령 호출에서 얻은 NextToken 값을 사용하여 다른 결과 페이지를 검색합니다. 이 경우 응답에는 NextToken 값이 포함되어 있지 않으므로 결과의 끝에 도달했음을 알 수 있습니다.

aws dynamodb list-tables \ --starting-token abCDeFGhiJKlmnOPqrSTuvwxYZ1aBCdEFghijK7LM51nOpqRSTuv3WxY3ZabC5dEFGhI2Jk3LmnoPQ6RST9

출력:

{ "TableNames": [ "Reply", "Thread" ] }

자세한 내용은 Amazon DynamoDB 개발자 안내서의 테이블 이름 나열을 참조하세요.

  • API 세부 정보는 AWS CLI 명령 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 var output *dynamodb.ListTablesOutput var err error tablePaginator := dynamodb.NewListTablesPaginator(basics.DynamoDbClient, &dynamodb.ListTablesInput{}) for tablePaginator.HasMorePages() { output, err = tablePaginator.NextPage(context.TODO()) if err != nil { log.Printf("Couldn't list tables. Here's why: %v\n", err) break } else { tableNames = append(tableNames, output.TableNames...) } } return tableNames, err }
  • API 세부 정보는 AWS SDK for Go API ListTables참조를 참조하십시오.

Java
SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.model.ListTablesRequest; import software.amazon.awssdk.services.dynamodb.model.ListTablesResponse; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ListTables { public static void main(String[] args) { System.out.println("Listing your Amazon DynamoDB tables:\n"); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); listAllTables(ddb); ddb.close(); } 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.x API ListTables참조를 참조하십시오.

JavaScript
JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import { ListTablesCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({}); export const main = async () => { const command = new ListTablesCommand({}); const response = await client.send(command); console.log(response); return response; };
JavaScript (v2) 용 SDK
참고

더 많은 내용이 있습니다. 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); } });
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 세부 정보는 Kotlin API용AWS SDK 레퍼런스를 참조하세요 ListTables.

PHP
SDK for PHP
참고

자세한 내용은 여기에서 확인할 수 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

public function listTables($exclusiveStartTableName = "", $limit = 100) { $this->dynamoDbClient->listTables([ 'ExclusiveStartTableName' => $exclusiveStartTableName, 'Limit' => $limit, ]); }
  • API 세부 정보는 AWS SDK for PHP API 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 # The table variable is set during the scenario in the call to # 'exists' if the table exists. Otherwise, it is set by 'create_table'. 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에 대한 자세한 내용은 파이썬용AWS SDK (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 Ruby API ListTables참조를 참조하십시오.

Rust
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에 대한 자세한 내용은 Rust용AWS SDK API 레퍼런스를 참조하십시오 ListTables.

SAP ABAP
SDK for SAP ABAP
참고

자세한 내용은 여기에서 확인할 수 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

TRY. oo_result = lo_dyn->listtables( ). " You can loop over the oo_result to get table properties like this. LOOP AT oo_result->get_tablenames( ) INTO DATA(lo_table_name). DATA(lv_tablename) = lo_table_name->get_value( ). ENDLOOP. DATA(lv_tablecount) = lines( oo_result->get_tablenames( ) ). MESSAGE 'Found ' && lv_tablecount && ' tables' TYPE 'I'. CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception). DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|. MESSAGE lv_error TYPE 'E'. ENDTRY.
  • API 세부 정보는 SAP용AWS SDK ABAP 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에 대한 자세한 내용은 Swift API용AWS SDK 레퍼런스를 참조하십시오 ListTables.

AWS SDK 개발자 가이드 및 코드 예제의 전체 목록은 을 참조하십시오. AWS SDK와 함께 DynamoDB 사용 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.