扫描 DynamoDB 表 - Amazon DynamoDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

扫描 DynamoDB 表

您可以使用 Amazon Web Services Management Console、Amazon CLI 或 Amazon SDK 对 DynamoDB 表执行扫描。有关扫描的更多信息,请参阅在 DynamoDB 中使用扫描

使用 Amazon SDK 扫描 DynamoDB 表

以下代码示例显示如何使用 Amazon SDK 扫描 DynamoDB 表。

.NET
Amazon SDK for .NET
提示

要了解如何设置和运行此示例,请参阅 GitHub

public static async Task<int> ScanTableAsync( AmazonDynamoDBClient client, string tableName, int startYear, int endYear) { var request = new ScanRequest { TableName = tableName, ExpressionAttributeNames = new Dictionary<string, string> { { "#yr", "year" }, }, ExpressionAttributeValues = new Dictionary<string, AttributeValue> { { ":y_a", new AttributeValue { N = startYear.ToString() } }, { ":y_z", new AttributeValue { N = endYear.ToString() } }, }, FilterExpression = "#yr between :y_a and :y_z", ProjectionExpression = "#yr, title, info.actors[0], info.directors, info.running_time_secs", }; // Keep track of how many movies were found. int foundCount = 0; var response = new ScanResponse(); do { response = await client.ScanAsync(request); foundCount += response.Items.Count; response.Items.ForEach(i => DisplayItem(i)); } while (response.LastEvaluatedKey.Count > 1); return foundCount; }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 Scan

C++
适用于 C++ 的 SDK
提示

要了解如何设置和运行此示例,请参阅 GitHub

Aws::Client::ClientConfiguration clientConfig; Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfig); Aws::DynamoDB::Model::ScanRequest req; req.SetTableName(table); if (!projection.empty()) req.SetProjectionExpression(projection); // Perform scan on table const Aws::DynamoDB::Model::ScanOutcome& result = dynamoClient.Scan(req); if (result.IsSuccess()) { // Reference the retrieved items const Aws::Vector<Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue>>& items = result.GetResult().GetItems(); if(items.size() > 0) { std::cout << "Number of items retrieved from scan: " << items.size() << std::endl; //Iterate each item and print for(const auto &item: items) { std::cout << "******************************************************" << std::endl; // Output each retrieved field and its value for (const auto& i : item) std::cout << i.first << ": " << i.second.GetS() << std::endl; } } else { std::cout << "No item found in table: " << table << std::endl; } } else { std::cout << "Failed to Scan items: " << result.GetError().GetMessage(); }
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 Scan

Go
SDK for Go V2
提示

要了解如何设置和运行此示例,请参阅 GitHub

// 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 } // Scan gets all movies in the DynamoDB table that were released in a range of years // and projects them to return a reduced set of fields. // The function uses the `expression` package to build the filter and projection // expressions. func (basics TableBasics) Scan(startYear int, endYear int) ([]Movie, error) { var movies []Movie var err error var response *dynamodb.ScanOutput filtEx := expression.Name("year").Between(expression.Value(startYear), expression.Value(endYear)) projEx := expression.NamesList( expression.Name("year"), expression.Name("title"), expression.Name("info.rating")) expr, err := expression.NewBuilder().WithFilter(filtEx).WithProjection(projEx).Build() if err != nil { log.Printf("Couldn't build expressions for scan. Here's why: %v\n", err) } else { response, err = basics.DynamoDbClient.Scan(context.TODO(), &dynamodb.ScanInput{ TableName: aws.String(basics.TableName), ExpressionAttributeNames: expr.Names(), ExpressionAttributeValues: expr.Values(), FilterExpression: expr.Filter(), ProjectionExpression: expr.Projection(), }) if err != nil { log.Printf("Couldn't scan for movies released between %v and %v. Here's why: %v\n", startYear, endYear, err) } else { err = attributevalue.UnmarshalListOfMaps(response.Items, &movies) if err != nil { log.Printf("Couldn't unmarshal query response. Here's why: %v\n", err) } } } return movies, err }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 Scan

Java
SDK for Java 2.x
提示

要了解如何设置和运行此示例,请参阅 GitHub

使用增强型客户端扫描 Amazon DynamoDB 表。

public static void scan( DynamoDbEnhancedClient enhancedClient) { try{ DynamoDbTable<Customer> custTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class)); Iterator<Customer> results = custTable.scan().items().iterator(); while (results.hasNext()) { Customer rec = results.next(); System.out.println("The record id is "+rec.getId()); System.out.println("The name is " +rec.getCustName()); } } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println("Done"); }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 Scan

JavaScript
SDK for JavaScript V3
提示

要了解如何设置和运行此示例,请参阅 GitHub

创建客户端。

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

创建 DynamoDB 文档客户端。

// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". const marshallOptions = { // Whether to automatically convert empty strings, blobs, and sets to `null`. convertEmptyValues: false, // false, by default. // Whether to remove undefined values while marshalling. removeUndefinedValues: false, // false, by default. // Whether to convert typeof object to map attribute. convertClassInstanceToMap: false, // false, by default. }; const unmarshallOptions = { // Whether to return numbers as a string instead of converting them to native JavaScript numbers. wrapNumbers: false, // false, by default. }; const translateConfig = { marshallOptions, unmarshallOptions }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, translateConfig); export { ddbDocClient };

使用 DynamoDB 文档客户端扫描表。

// Import required AWS SDK clients and commands for Node.js. import { ddbDocClient } from "../libs/ddbDocClient.js"; import { ScanCommand } from "@aws-sdk/lib-dynamodb"; // Set the parameters. export const params = { TableName: "TABLE_NAME", ProjectionExpression: "#r, #y, title", ExpressionAttributeNames: { "#r": "rank", "#y": "year" }, FilterExpression: "title = :t and #y = :y and info.#r = :r", ExpressionAttributeValues: { ":r": "MOVIE_RANK", ":y": "MOVIE_YEAR", ":t": "MOVIE_NAME", }, }; export const scanTable = async () => { try { const data = await ddbDocClient.send(new ScanCommand(params)); console.log("success", data.Items); } catch (err) { console.log("Error", err); } }; scanTable();
  • 有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 Scan

SDK for JavaScript V2
提示

要了解如何设置和运行此示例,请参阅 GitHub

// Load the AWS SDK for Node.js. var AWS = require("aws-sdk"); // Set the AWS Region. AWS.config.update({ region: "REGION" }); // Create DynamoDB service object. var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); const params = { // Specify which items in the results are returned. FilterExpression: "Subtitle = :topic AND Season = :s AND Episode = :e", // Define the expression attribute value, which are substitutes for the values you want to compare. ExpressionAttributeValues: { ":topic": {S: "SubTitle2"}, ":s": {N: 1}, ":e": {N: 2}, }, // Set the projection expression, which are the attributes that you want. ProjectionExpression: "Season, Episode, Title, Subtitle", TableName: "EPISODES_TABLE", }; ddb.scan(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); data.Items.forEach(function (element, index, array) { console.log( "printing", element.Title.S + " (" + element.Subtitle.S + ")" ); }); } });
Kotlin
SDK for Kotlin
注意

这是适用于预览版中功能的预发行文档。本文档随时可能更改。

提示

要了解如何设置和运行此示例,请参阅 GitHub

suspend fun scanItems(tableNameVal: String) { val request = ScanRequest { tableName = tableNameVal } DynamoDbClient { region = "us-east-1" }.use { ddb -> val response = ddb.scan(request) response.items?.forEach { item -> item.keys.forEach { key -> println("The key name is $key\n") println("The value is ${item[key]}") } } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 Scan

Python
适用于 Python (Boto3) 的 SDK
提示

要了解如何设置和运行此示例,请参阅 GitHub

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 scan_movies(self, year_range): """ Scans for movies that were released in a range of years. Uses a projection expression to return a subset of data for each movie. :param year_range: The range of years to retrieve. :return: The list of movies released in the specified years. """ movies = [] scan_kwargs = { 'FilterExpression': Key('year').between(year_range['first'], year_range['second']), 'ProjectionExpression': "#yr, title, info.rating", 'ExpressionAttributeNames': {"#yr": "year"}} try: done = False start_key = None while not done: if start_key: scan_kwargs['ExclusiveStartKey'] = start_key response = self.table.scan(**scan_kwargs) movies.extend(response.get('Items', [])) start_key = response.get('LastEvaluatedKey', None) done = start_key is None except ClientError as err: logger.error( "Couldn't scan for movies. Here's why: %s: %s", err.response['Error']['Code'], err.response['Error']['Message']) raise return movies
  • 有关 API 详细信息,请参阅《适用于 Python (Boto3) 的 Amazon SDK API 参考》中的 Scan

Ruby
SDK for Ruby
提示

要了解如何设置和运行此示例,请参阅 GitHub

# Scans for movies that were released in a range of years. # Uses a projection expression to return a subset of data for each movie. # # @param year_range [Hash] The range of years to retrieve. # @return [Array] The list of movies released in the specified years. def scan_movies(year_range) movies = [] scan_hash = { filter_expression: "#yr between :start_yr and :end_yr", projection_expression: "#yr, title, info.rating", expression_attribute_names: {"#yr" => "year"}, expression_attribute_values: { ":start_yr" => year_range[:start], ":end_yr" => year_range[:end]} } done = false start_key = nil until done scan_hash[:exclusive_start_key] = start_key unless start_key.nil? response = @table.scan(scan_hash) movies.concat(response.items) unless response.items.nil? start_key = response.last_evaluated_key done = start_key.nil? end rescue Aws::Errors::ServiceError => e puts("Couldn't scan for movies. Here's why:") puts("\t#{e.code}: #{e.message}") raise else movies end
  • 有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 Scan

Rust
SDK for Rust
注意

本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。

提示

要了解如何设置和运行此示例,请参阅 GitHub

async fn list_items(client: &Client, table: &str) -> Result<(), Error> { let items: Result<Vec<_>, _> = client .scan() .table_name(table) .into_paginator() .items() .send() .collect() .await; println!("Items in table:"); for item in items? { println!(" {:?}", item); } Ok(()) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 Scan

有关更多 DynamoDB 示例,请参阅适用于使用 Amazon SDK 的 DynamoDB 的代码示例