获取有关 DynamoDB 表的信息 - Amazon DynamoDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

获取有关 DynamoDB 表的信息

以下代码示例演示了如何获取有关 DynamoDB 表的信息。

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

.NET
Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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}"); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NET API 参考DescribeTable中的。

Bash
Amazon CLI 使用 Bash 脚本
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

############################################################################### # 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 }

本示例中使用的实用程序函数。

############################################################################### # 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 的详细信息,请参阅Amazon CLI 命令参考DescribeTable中的。

C++
适用于 C++ 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

//! 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(); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for C++ API 参考DescribeTable中的。

CLI
Amazon CLI

描述表

以下 describe-table 示例将描述 MusicCollection 表。

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

输出:

{ "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 } }

有关更多信息,请参阅《Amazon DynamoDB 开发人员指南》中的描述表

  • 有关 API 的详细信息,请参阅Amazon CLI 命令参考DescribeTable中的。

Go
适用于 Go V2 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

// 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 }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Go API 参考DescribeTable中的。

Java
适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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!"); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考DescribeTable中的。

JavaScript
适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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; };
适用于 JavaScript (v2) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

// 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
适用于 Python (Boto3) 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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
  • 有关 API 的详细信息,请参阅适用DescribeTablePython 的 Amazon SDK (Boto3) API 参考

Ruby
适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# 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 的详细信息,请参阅 Amazon SDK for Ruby API 参考DescribeTable中的。

SAP ABAP
SDK for SAP ABAP
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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.
  • 有关 API 的详细信息,请参阅适用DescribeTable于 S AP 的 Amazon SDK ABAP API 参考

有关 S Amazon DK 开发者指南和代码示例的完整列表,请参阅结合使用 DynamoDB 与 Amazon SDK。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。