Abrufen von Informationen zu einer DynamoDB-Tabelle - AWS SDK-Codebeispiele

Weitere AWS SDK-Beispiele finden Sie im AWS Doc SDK Examples GitHub Repo.

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

Abrufen von Informationen zu einer DynamoDB-Tabelle

In den folgenden Codebeispielen wird gezeigt, wie Informationen zu einer DynamoDB-Tabelle abgerufen werden.

Beispiele für Aktionen sind Codeauszüge aus größeren Programmen und müssen im Kontext ausgeführt werden. Im folgenden Codebeispiel können Sie diese Aktion im Kontext sehen:

.NET
AWS SDK for .NET
Anmerkung

Auf gibt es mehr GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS-Code-Beispiel-Repository einrichten und ausführen.

private static async Task GetTableInformation() { Console.WriteLine("\n*** Retrieving table information ***"); var response = await Client.DescribeTableAsync(new DescribeTableRequest { TableName = ExampleTableName }); var table = response.Table; Console.WriteLine($"Name: {table.TableName}"); Console.WriteLine($"# of items: {table.ItemCount}"); Console.WriteLine($"Provision Throughput (reads/sec): " + $"{table.ProvisionedThroughput.ReadCapacityUnits}"); Console.WriteLine($"Provision Throughput (writes/sec): " + $"{table.ProvisionedThroughput.WriteCapacityUnits}"); }
  • Weitere API-Informationen finden Sie unter DescribeTable in der APIAWS SDK for .NET-Referenz zu .

Bash
AWS CLI mit Bash-Skript
Anmerkung

Auf gibt es mehr GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS-Code-Beispiel-Repository einrichten und ausführen.

############################################################################### # function dynamodb_describe_table # # This function returns the status of a DynamoDB table. # # Parameters: # -n table_name -- The name of the table. # # Response: # - TableStatus: # And: # 0 - Table is active. # 1 - If it fails. ############################################################################### function dynamodb_describe_table { local table_name local option OPTARG # Required to use getopts command in a function. ####################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_describe_table" echo "Describe the status of a DynamoDB table." echo " -n table_name -- The name of the table." echo "" } # Retrieve the calling parameters. while getopts "n:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi local table_status table_status=$( aws dynamodb describe-table \ --table-name "$table_name" \ --output text \ --query 'Table.TableStatus' ) local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log "$error_code" errecho "ERROR: AWS reports describe-table operation failed.$table_status" return 1 fi echo "$table_status" return 0 }

Die in diesem Beispiel verwendeten Dienstprogrammfunktionen.

############################################################################### # 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-Details finden Sie unter DescribeTable in der AWS CLI -Befehlsreferenz.

C++
SDK für C++
Anmerkung

Auf gibt es mehr GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS-Code-Beispiel-Repository einrichten und ausführen.

//! Describe an Amazon DynamoDB table. /*! \sa describeTable() \param tableName: The DynamoDB table name. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::DynamoDB::describeTable(const Aws::String &tableName, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration); Aws::DynamoDB::Model::DescribeTableRequest request; request.SetTableName(tableName); const Aws::DynamoDB::Model::DescribeTableOutcome &outcome = dynamoClient.DescribeTable( request); if (outcome.IsSuccess()) { const Aws::DynamoDB::Model::TableDescription &td = outcome.GetResult().GetTable(); std::cout << "Table name : " << td.GetTableName() << std::endl; std::cout << "Table ARN : " << td.GetTableArn() << std::endl; std::cout << "Status : " << Aws::DynamoDB::Model::TableStatusMapper::GetNameForTableStatus( td.GetTableStatus()) << std::endl; std::cout << "Item count : " << td.GetItemCount() << std::endl; std::cout << "Size (bytes): " << td.GetTableSizeBytes() << std::endl; const Aws::DynamoDB::Model::ProvisionedThroughputDescription &ptd = td.GetProvisionedThroughput(); std::cout << "Throughput" << std::endl; std::cout << " Read Capacity : " << ptd.GetReadCapacityUnits() << std::endl; std::cout << " Write Capacity: " << ptd.GetWriteCapacityUnits() << std::endl; const Aws::Vector<Aws::DynamoDB::Model::AttributeDefinition> &ad = td.GetAttributeDefinitions(); std::cout << "Attributes" << std::endl; for (const auto &a: ad) std::cout << " " << a.GetAttributeName() << " (" << Aws::DynamoDB::Model::ScalarAttributeTypeMapper::GetNameForScalarAttributeType( a.GetAttributeType()) << ")" << std::endl; } else { std::cerr << "Failed to describe table: " << outcome.GetError().GetMessage(); } return outcome.IsSuccess(); }
  • Weitere API-Informationen finden Sie unter DescribeTable in der APIAWS SDK for C++-Referenz zu .

CLI
AWS CLI

So beschreiben Sie eine Tabelle

Im folgenden describe-table Beispiel wird die MusicCollection Tabelle beschrieben.

aws dynamodb describe-table \ --table-name MusicCollection

Ausgabe:

{ "Table": { "AttributeDefinitions": [ { "AttributeName": "Artist", "AttributeType": "S" }, { "AttributeName": "SongTitle", "AttributeType": "S" } ], "ProvisionedThroughput": { "NumberOfDecreasesToday": 0, "WriteCapacityUnits": 5, "ReadCapacityUnits": 5 }, "TableSizeBytes": 0, "TableName": "MusicCollection", "TableStatus": "ACTIVE", "KeySchema": [ { "KeyType": "HASH", "AttributeName": "Artist" }, { "KeyType": "RANGE", "AttributeName": "SongTitle" } ], "ItemCount": 0, "CreationDateTime": 1421866952.062 } }

Weitere Informationen finden Sie unter Beschreiben einer Tabelle im Amazon-DynamoDBDynamoDB-Entwicklerhandbuch.

  • API-Details finden Sie unter DescribeTable in der AWS CLI -Befehlsreferenz.

Go
SDK für Go V2
Anmerkung

Auf gibt es mehr GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS-Code-Beispiel-Repository einrichten und ausführen.

// 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 } // TableExists determines whether a DynamoDB table exists. func (basics TableBasics) TableExists() (bool, error) { exists := true _, err := basics.DynamoDbClient.DescribeTable( context.TODO(), &dynamodb.DescribeTableInput{TableName: aws.String(basics.TableName)}, ) if err != nil { var notFoundEx *types.ResourceNotFoundException if errors.As(err, &notFoundEx) { log.Printf("Table %v does not exist.\n", basics.TableName) err = nil } else { log.Printf("Couldn't determine existence of table %v. Here's why: %v\n", basics.TableName, err) } exists = false } return exists, err }
  • Weitere API-Informationen finden Sie unter DescribeTable in der APIAWS SDK for Go-Referenz für .

Java
SDK für Java 2.x
Anmerkung

Auf gibt es mehr GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS-Code-Beispiel-Repository einrichten und ausführen.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputDescription; import software.amazon.awssdk.services.dynamodb.model.TableDescription; 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 DescribeTable { public static void main(String[] args) { final String usage = """ Usage: <tableName> Where: tableName - The Amazon DynamoDB table to get information about (for example, Music3). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String tableName = args[0]; System.out.format("Getting description for %s\n\n", tableName); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); describeDymamoDBTable(ddb, tableName); ddb.close(); } public static void describeDymamoDBTable(DynamoDbClient ddb, String tableName) { DescribeTableRequest request = DescribeTableRequest.builder() .tableName(tableName) .build(); try { TableDescription tableInfo = ddb.describeTable(request).table(); if (tableInfo != null) { System.out.format("Table name : %s\n", tableInfo.tableName()); System.out.format("Table ARN : %s\n", tableInfo.tableArn()); System.out.format("Status : %s\n", tableInfo.tableStatus()); System.out.format("Item count : %d\n", tableInfo.itemCount()); System.out.format("Size (bytes): %d\n", tableInfo.tableSizeBytes()); ProvisionedThroughputDescription throughputInfo = tableInfo.provisionedThroughput(); System.out.println("Throughput"); System.out.format(" Read Capacity : %d\n", throughputInfo.readCapacityUnits()); System.out.format(" Write Capacity: %d\n", throughputInfo.writeCapacityUnits()); List<AttributeDefinition> attributes = tableInfo.attributeDefinitions(); System.out.println("Attributes"); for (AttributeDefinition a : attributes) { System.out.format(" %s (%s)\n", a.attributeName(), a.attributeType()); } } } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println("\nDone!"); } }
  • Weitere API-Informationen finden Sie unter DescribeTable in der APIAWS SDK for Java 2.x-Referenz für .

JavaScript
SDK für JavaScript (v3)
Anmerkung

Auf gibt es mehr GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS-Code-Beispiel-Repository einrichten und ausführen.

import { DescribeTableCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({}); export const main = async () => { const command = new DescribeTableCommand({ TableName: "Pastries", }); const response = await client.send(command); console.log(`TABLE NAME: ${response.Table.TableName}`); console.log(`TABLE ITEM COUNT: ${response.Table.ItemCount}`); return response; };
SDK für JavaScript (v2)
Anmerkung

Auf gibt es mehr GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS-Code-Beispiel-Repository einrichten und ausführen.

// 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" }); var params = { TableName: process.argv[2], }; // Call DynamoDB to retrieve the selected table descriptions ddb.describeTable(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.Table.KeySchema); } });
Python
SDK für Python (Boto3)
Anmerkung

Auf gibt es mehr GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS-Code-Beispiel-Repository einrichten und ausführen.

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 exists(self, table_name): """ Determines whether a table exists. As a side effect, stores the table in a member variable. :param table_name: The name of the table to check. :return: True when the table exists; otherwise, False. """ try: table = self.dyn_resource.Table(table_name) table.load() exists = True except ClientError as err: if err.response["Error"]["Code"] == "ResourceNotFoundException": exists = False else: logger.error( "Couldn't check for existence of %s. Here's why: %s: %s", table_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: self.table = table return exists
  • Weitere API-Informationen finden Sie unter DescribeTable in der AWS API-Referenz zum -SDK für Python (Boto3).

Ruby
SDK für Ruby
Anmerkung

Auf gibt es mehr GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS-Code-Beispiel-Repository einrichten und ausführen.

# 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
  • Weitere API-Informationen finden Sie unter DescribeTable in der APIAWS SDK for Ruby-Referenz für .

SAP ABAP
SDK für SAP ABAP
Anmerkung

Auf gibt es mehr GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS-Code-Beispiel-Repository einrichten und ausführen.

TRY. oo_result = lo_dyn->describetable( iv_tablename = iv_table_name ). DATA(lv_tablename) = oo_result->get_table( )->ask_tablename( ). DATA(lv_tablearn) = oo_result->get_table( )->ask_tablearn( ). DATA(lv_tablestatus) = oo_result->get_table( )->ask_tablestatus( ). DATA(lv_itemcount) = oo_result->get_table( )->ask_itemcount( ). MESSAGE 'The table name is ' && lv_tablename && '. The table ARN is ' && lv_tablearn && '. The tablestatus is ' && lv_tablestatus && '. Item count is ' && lv_itemcount TYPE 'I'. CATCH /aws1/cx_dynresourcenotfoundex. MESSAGE 'The table ' && lv_tablename && ' does not exist' TYPE 'E'. ENDTRY.
  • Weitere API-Informationen finden Sie unter DescribeTable in der AWS API-Referenz zum -SDK für SAP ABAP.