DynamoDB テーブルに対してクエリを実行する - Amazon DynamoDB

DynamoDB テーブルに対してクエリを実行する

AWS Management Console、AWS CLI、または AWS SDK を使用して DynamoDB テーブルでクエリを実行できます。クエリの詳細については、「DynamoDB のクエリオペレーション」を参照してください。

AWS SDK を使用して、DynamoDB テーブルに対してクエリを実行する

次のコード例は、AWS SDK を使用して DynamoDB テーブルに対してクエリを実行する方法を示しています。

.NET
AWS SDK for .NET
ヒント

この例を設定および実行する方法については、「GitHub」を参照してください。

/// <summary> /// Queries the table for movies released in a particular year and /// then displays the information for the movies returned. /// </summary> /// <param name="client">The initialized DynamoDB client object.</param> /// <param name="tableName">The name of the table to query.</param> /// <param name="year">The release year for which we want to /// view movies.</param> /// <returns>The number of movies that match the query.</returns> public static async Task<int> QueryMoviesAsync(AmazonDynamoDBClient client, string tableName, int year) { var movieTable = Table.LoadTable(client, tableName); var filter = new QueryFilter("year", QueryOperator.Equal, year); Console.WriteLine("\nFind movies released in: {year}:"); var config = new QueryOperationConfig() { Limit = 10, // 10 items per page. Select = SelectValues.SpecificAttributes, AttributesToGet = new List<string> { "title", "year", }, ConsistentRead = true, Filter = filter, }; // Value used to track how many movies match the // supplied criteria. var moviesFound = 0; Search search = movieTable.Query(config); do { var movieList = await search.GetNextSetAsync(); moviesFound += movieList.Count; foreach (var movie in movieList) { DisplayDocument(movie); } } while (!search.IsDone); return moviesFound; }
C++
SDK for C++
ヒント

この例を設定および実行する方法については、「GitHub」を参照してください。

Aws::Client::ClientConfiguration clientConfig; Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfig); Aws::DynamoDB::Model::QueryRequest req; req.SetTableName(table); // Set query key condition expression req.SetKeyConditionExpression(partitionKeyAttributeName + "= :valueToMatch"); // Set Expression AttributeValues Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> attributeValues; attributeValues.emplace(":valueToMatch", partitionKeyAttributeValue); req.SetExpressionAttributeValues(attributeValues); // Perform Query operation const Aws::DynamoDB::Model::QueryOutcome& result = dynamoClient.Query(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 Query: " << 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 Query items: " << result.GetError().GetMessage(); }
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 } // Query gets all movies in the DynamoDB table that were released in the specified year. // The function uses the `expression` package to build the key condition expression // that is used in the query. func (basics TableBasics) Query(releaseYear int) ([]Movie, error) { var err error var response *dynamodb.QueryOutput var movies []Movie keyEx := expression.Key("year").Equal(expression.Value(releaseYear)) expr, err := expression.NewBuilder().WithKeyCondition(keyEx).Build() if err != nil { log.Printf("Couldn't build epxression for query. Here's why: %v\n", err) } else { response, err = basics.DynamoDbClient.Query(context.TODO(), &dynamodb.QueryInput{ TableName: aws.String(basics.TableName), ExpressionAttributeNames: expr.Names(), ExpressionAttributeValues: expr.Values(), KeyConditionExpression: expr.KeyCondition(), }) if err != nil { log.Printf("Couldn't query for movies released in %v. Here's why: %v\n", releaseYear, 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 }
Java
SDK for Java 2.x
ヒント

この例を設定および実行する方法については、「GitHub」を参照してください。

拡張クライアントを使用してテーブルに対してクエリを実行します。

public static String queryTable(DynamoDbEnhancedClient enhancedClient) { try{ DynamoDbTable<Customer> mappedTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class)); QueryConditional queryConditional = QueryConditional .keyEqualTo(Key.builder() .partitionValue("id101") .build()); // Get items in the table and write out the ID value. Iterator<Customer> results = mappedTable.query(queryConditional).items().iterator(); String result=""; while (results.hasNext()) { Customer rec = results.next(); result = rec.getId(); System.out.println("The record id is "+result); } return result; } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } return ""; }

拡張クライアントとセカンダリインデックスを使用してテーブルに対してクエリを実行します。

public static void queryIndex(DynamoDbClient ddb, String tableName) { try { // Create a DynamoDbEnhancedClient and use the DynamoDbClient object. DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); //Create a DynamoDbTable object based on Movies. DynamoDbTable<Movies> table = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); String dateVal = "2013"; DynamoDbIndex<Movies> secIndex = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)) .index("year-index"); AttributeValue attVal = AttributeValue.builder() .n(dateVal) .build(); // Create a QueryConditional object that's used in the query operation. QueryConditional queryConditional = QueryConditional .keyEqualTo(Key.builder().partitionValue(attVal) .build()); // Get items in the table. SdkIterable<Page<Movies>> results = secIndex.query( QueryEnhancedRequest.builder() .queryConditional(queryConditional) .limit(300) .build()); //Display the results. results.forEach(page -> { List<Movies> allMovies = page.items(); for (Movies myMovies: allMovies) { System.out.println("The movie title is " + myMovies.getTitle() + ". The year is " + myMovies.getYear()); } }); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } }

DynamoDbClient を使用してテーブルに対してクエリを実行します。

public static int queryTable(DynamoDbClient ddb, String tableName, String partitionKeyName, String partitionKeyVal, String partitionAlias) { // Set up an alias for the partition key name in case it's a reserved word. HashMap<String,String> attrNameAlias = new HashMap<String,String>(); attrNameAlias.put(partitionAlias, partitionKeyName); // Set up mapping of the partition name with the value. HashMap<String, AttributeValue> attrValues = new HashMap<>(); attrValues.put(":"+partitionKeyName, AttributeValue.builder() .s(partitionKeyVal) .build()); QueryRequest queryReq = QueryRequest.builder() .tableName(tableName) .keyConditionExpression(partitionAlias + " = :" + partitionKeyName) .expressionAttributeNames(attrNameAlias) .expressionAttributeValues(attrValues) .build(); try { QueryResponse response = ddb.query(queryReq); return response.count(); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } return -1; }

DynamoDbClient とセカンダリインデックスを使用してテーブルに対してクエリを実行します。

public static void queryIndex(DynamoDbClient ddb, String tableName) { try { Map<String,String> expressionAttributesNames = new HashMap<>(); expressionAttributesNames.put("#year","year"); Map<String, AttributeValue> expressionAttributeValues = new HashMap<>(); expressionAttributeValues.put(":yearValue", AttributeValue.builder().n("2013").build()); QueryRequest request = QueryRequest.builder() .tableName(tableName) .indexName("year-index") .keyConditionExpression("#year = :yearValue") .expressionAttributeNames(expressionAttributesNames) .expressionAttributeValues(expressionAttributeValues) .build(); System.out.println("=== Movie Titles ==="); QueryResponse response = ddb.query(request); response.items() .forEach(movie-> System.out.println(movie.get("title").s())); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } }
JavaScript
SDK for JavaScript V3
ヒント

この例を設定および実行する方法については、「GitHub」を参照してください。

クライアントを作成します。

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

テーブルに対してクエリを実行します。

// Import required AWS SDK clients and commands for Node.js import { QueryCommand } from "@aws-sdk/client-dynamodb"; import { ddbClient } from "./libs/ddbClient.js"; // Set the parameters export const params = { KeyConditionExpression: "Season = :s and Episode > :e", FilterExpression: "contains (Subtitle, :topic)", ExpressionAttributeValues: { ":s": { N: "1" }, ":e": { N: "2" }, ":topic": { S: "SubTitle" }, }, ProjectionExpression: "Episode, Title, Subtitle", TableName: "EPISODES_TABLE", }; export const run = async () => { try { const data = await ddbClient.send(new QueryCommand(params)); return data; data.Items.forEach(function (element, index, array) { console.log(element.Title.S + " (" + element.Subtitle.S + ")"); }); } catch (err) { console.error(err); } }; run();

DynamoDB ドキュメントクライアントのクライアントを作成します。

// Create service client module using ES6 syntax. import { DynamoDBDocumentClient} from "@aws-sdk/lib-dynamodb"; import {ddbClient} from "./ddbClient"; 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 { QueryCommand } from "@aws-sdk/lib-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; // Set the parameters. export const params = { ExpressionAttributeNames: { "#r": "rank", "#y": "year" }, ProjectionExpression: "#r, #y, title", TableName: "TABLE_NAME", ExpressionAttributeValues: { ":t": "MOVIE_NAME", ":y": "MOVIE_YEAR", ":r": "MOVIE_RANK", }, KeyConditionExpression: "title = :t and #y = :y", FilterExpression: "info.#r = :r", }; export const queryTable = async () => { try { const data = await ddbDocClient.send(new QueryCommand(params)); for (let i = 0; i < data.Items.length; i++) { console.log( "Success. Items with rank of " + "MOVIE_RANK" + " include\n" + "Year = " + data.Items[i].year + " Title = " + data.Items[i].title ); } } catch (err) { console.log("Error", err); } }; queryTable();
SDK for JavaScript V2
ヒント

この例を設定および実行する方法については、「GitHub」を参照してください。

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create DynamoDB document client var docClient = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); var params = { ExpressionAttributeValues: { ':s': 2, ':e': 9, ':topic': 'PHRASE' }, KeyConditionExpression: 'Season = :s and Episode > :e', FilterExpression: 'contains (Subtitle, :topic)', TableName: 'EPISODES_TABLE' }; docClient.query(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.Items); } });
Kotlin
SDK for Kotlin
注記

これはプレビューリリースの機能に関するプレリリースドキュメントです。このドキュメントは変更される可能性があります。

ヒント

この例を設定および実行する方法については、「GitHub」を参照してください。

suspend fun queryDynTable( tableNameVal: String, partitionKeyName: String, partitionKeyVal: String, partitionAlias: String ): Int { val attrNameAlias = mutableMapOf<String, String>() attrNameAlias[partitionAlias] = partitionKeyName // Set up mapping of the partition name with the value. val attrValues = mutableMapOf<String, AttributeValue>() attrValues[":$partitionKeyName"] = AttributeValue.S(partitionKeyVal) val request = QueryRequest { tableName = tableNameVal keyConditionExpression = "$partitionAlias = :$partitionKeyName" expressionAttributeNames = attrNameAlias this.expressionAttributeValues = attrValues } DynamoDbClient { region = "us-east-1" }.use { ddb -> val response = ddb.query(request) return response.count } }
PHP
SDK for PHP
ヒント

この例を設定および実行する方法については、「GitHub」を参照してください。

$birthKey = [ 'Key' => [ 'year' => [ 'N' => "$birthYear", ], ], ]; $result = $service->query($tableName, $birthKey); public function query(string $tableName, $key) { $expressionAttributeValues = []; $expressionAttributeNames = []; $keyConditionExpression = ""; $index = 1; foreach ($key as $name => $value) { $keyConditionExpression .= "#" . array_key_first($value) . " = :v$index,"; $expressionAttributeNames["#" . array_key_first($value)] = array_key_first($value); $hold = array_pop($value); $expressionAttributeValues[":v$index"] = [ array_key_first($hold) => array_pop($hold), ]; } $keyConditionExpression = substr($keyConditionExpression, 0, -1); $query = [ 'ExpressionAttributeValues' => $expressionAttributeValues, 'ExpressionAttributeNames' => $expressionAttributeNames, 'KeyConditionExpression' => $keyConditionExpression, 'TableName' => $tableName, ]; return $this->dynamoDbClient->query($query); }
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 query_movies(self, year): """ Queries for movies that were released in the specified year. :param year: The year to query. :return: The list of movies that were released in the specified year. """ try: response = self.table.query(KeyConditionExpression=Key('year').eq(year)) except ClientError as err: logger.error( "Couldn't query for movies released in %s. Here's why: %s: %s", year, err.response['Error']['Code'], err.response['Error']['Message']) raise else: return response['Items']

項目に対してクエリを実行し、データのサブセットを返すように射影します。

class UpdateQueryWrapper: def __init__(self, table): self.table = table def query_and_project_movies(self, year, title_bounds): """ Query for movies that were released in a specified year and that have titles that start within a range of letters. A projection expression is used to return a subset of data for each movie. :param year: The release year to query. :param title_bounds: The range of starting letters to query. :return: The list of movies. """ try: response = self.table.query( ProjectionExpression="#yr, title, info.genres, info.actors[0]", ExpressionAttributeNames={"#yr": "year"}, KeyConditionExpression=( Key('year').eq(year) & Key('title').between(title_bounds['first'], title_bounds['second']))) except ClientError as err: if err.response['Error']['Code'] == "ValidationException": logger.warning( "There's a validation error. Here's the message: %s: %s", err.response['Error']['Code'], err.response['Error']['Message']) else: logger.error( "Couldn't query for movies. Here's why: %s: %s", err.response['Error']['Code'], err.response['Error']['Message']) raise else: return response['Items']
Ruby
SDK for Ruby
ヒント

この例を設定および実行する方法については、「GitHub」を参照してください。

# Queries for movies that were released in the specified year. # # @param year [Integer] The year to query. # @return [Array] The list of movies that were released in the specified year. def query_movies(year) response = @table.query( key_condition_expression: "#yr = :year", expression_attribute_names: {"#yr" => "year"}, expression_attribute_values: {":year" => year}) rescue Aws::Errors::ServiceError => e puts("Couldn't query for movies released in #{year}. Here's why:") puts("\t#{e.code}: #{e.message}") raise else response.items end
Rust
SDK for Rust
注記

これはプレビューリリースの SDK に関するドキュメントです。SDK は変更される場合があり、本稼働環境では使用しないでください。

ヒント

この例を設定および実行する方法については、「GitHub」を参照してください。

指定した年に作られた映画を検索します。

fn movies_in_year(client: &Client, table_name: &str, year: u16) -> Query { client .query() .table_name(table_name) .key_condition_expression("#yr = :yyyy") .expression_attribute_names("#yr", "year") .expression_attribute_values(":yyyy", AttributeValue::N(year.to_string())) }
  • API の詳細については、AWS SDK for Rust API リファレンスの「Query」を参照してください。

DynamoDB のその他の例については、「AWS SDK を使用した DynamoDB のコード例」を参照してください。