DynamoDB テーブルをスキャンする
AWS Management Console、AWS CLI、または AWS SDK を使用して DynamoDB テーブルのスキャンを実行できます。スキャンの詳細については、「DynamoDB でのスキャンの使用」を参照してください。
AWS SDK を使用して、DynamoDB テーブルをスキャンする
次のコード例は、AWS SDK を使用して DynamoDB テーブルをスキャンする方法を示しています。
- .NET
-
- AWS 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 の詳細については、AWS SDK for .NET API リファレンスの「Scan」を参照してください。
-
- C++
-
- SDK for C++
-
ヒント この例を設定および実行する方法については、「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 の詳細については、AWS 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 の詳細については、AWS 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 の詳細については、AWS 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 の詳細については、AWS 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 + ")" ); }); } });
-
詳細については、「AWS SDK for JavaScript デベロッパーガイド」を参照してください。
-
API の詳細については、AWS SDK for JavaScript API リファレンスの「Scan」を参照してください。
-
- 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 の詳細については、AWS SDK for Kotlin API リファレンス
の「Scan」を参照してください。
-
- PHP
-
- SDK for PHP
-
ヒント この例を設定および実行する方法については、「GitHub
」を参照してください。 $yearsKey = [ 'Key' => [ 'year' => [ 'N' => [ 'minRange' => 1990, 'maxRange' => 1999, ], ], ], ]; $filter = "year between 1990 and 1999"; echo "\nHere's a list of all the movies released in the 90s:\n"; $result = $service->scan($tableName, $yearsKey, $filter); foreach ($result['Items'] as $movie) { $movie = $marshal->unmarshalItem($movie); echo $movie['title'] . "\n"; } public function scan(string $tableName, array $key, string $filters) { $query = [ 'ExpressionAttributeNames' => ['#year' => 'year'], 'ExpressionAttributeValues' => [ ":min" => ['N' => '1990'], ":max" => ['N' => '1999'], ], 'FilterExpression' => "#year between :min and :max", 'TableName' => $tableName, ]; return $this->dynamoDbClient->scan($query); }
-
API の詳細については、AWS SDK for PHP API リファレンスの「Scan」を参照してください。
-
- Python
-
- SDK for Python (Boto3)
-
ヒント この例を設定および実行する方法については、「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 の詳細については、AWS SDK for Python (Boto3) 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 の詳細については、AWS SDK for Ruby API リファレンスの「Scan」を参照してください。
-
- Rust
-
- SDK for Rust
-
注記 これはプレビューリリースの SDK に関するドキュメントです。SDK は変更される場合があり、本稼働環境では使用しないでください。
ヒント この例を設定および実行する方法については、「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 の詳細については、AWS SDK for Rust API リファレンスの「Scan
」を参照してください。
-
DynamoDB のその他の例については、「AWS SDK を使用した DynamoDB のコード例」を参照してください。