Interroger une table DynamoDB à l'aide d'un kit AWS SDK - Amazon DynamoDB

Interroger une table DynamoDB à l'aide d'un kit AWS SDK

Les exemples de code suivants montrent comment interroger des tables DynamoDB.

.NET
AWS SDK for .NET
Astuce

Pour découvrir les étapes de configuration et d’exécution de cet exemple, consultez 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; }
  • Pour plus d'informations sur l'API, consultez Requête dans la référence d'API AWS SDK for .NET.

C++
Kit SDK pour C++
Astuce

Pour découvrir les étapes de configuration et d’exécution de cet exemple, consultez 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(); }
  • Pour plus d'informations sur l'API, consultez Requête dans la référence d'API AWS SDK for C++.

Go
Kit SDK for Go V2
Astuce

Pour découvrir les étapes de configuration et d’exécution de cet exemple, consultez 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 }
  • Pour plus d'informations sur l'API, consultez Requête dans la référence d'API AWS SDK for Go.

Java
Kit SDK pour Java 2.x
Astuce

Pour découvrir comment configurer et exécuter cet exemple, consultez GitHub.

Interroge une table à l'aide du client amélioré.

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

Interroge une table à l'aide du client amélioré et d'un index secondaire.

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); } }

Interroge une table à l'aide du 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; }

Interroge une table à l'aide du DynamoDbClient et d'un index secondaire.

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); } }
  • Pour plus d'informations sur l'API, consultez Requête dans la référence d'API AWS SDK for Java 2.x.

JavaScript
Kit SDK pour JavaScript V3
Astuce

Pour découvrir les étapes de configuration et d’exécution de cet exemple, consultez GitHub.

Créez le client.

// 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 };

Interrogez la table.

// 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)); data.Items.forEach(function (element) { console.log(element.Title.S + " (" + element.Subtitle.S + ")"); }); return data; } catch (err) { console.error(err); } }; run();

Créez le client pour le client de document 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 };

Interrogez la table à l'aide du client de document 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();
Kit SDK pour JavaScript V2
Astuce

Pour découvrir les étapes de configuration et d’exécution de cet exemple, consultez 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
Kits SDK pour Kotlin
Note

Ceci est une documentation préliminaire pour une fonctionnalité en version de prévisualisation. Elle est susceptible d’être modifiée.

Astuce

Pour découvrir comment configurer et exécuter cet exemple, consultez 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 } }
  • Pour plus d'informations sur l'API, consultez Requête dans la référence d'API du kit AWS SDK pour Kotlin.

PHP
Kit SDK pour PHP
Astuce

Pour découvrir les étapes de configuration et d’exécution de cet exemple, consultez 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); }
  • Pour plus d'informations sur l'API, consultez Requête dans la référence d'API AWS SDK for PHP.

Python
Kit SDK pour Python (Boto3)
Astuce

Pour découvrir les étapes de configuration et d’exécution de cet exemple, consultez GitHub.

Interrogez des éléments à l'aide d'une expression de condition clé.

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']

Interrogez des éléments et projetez-les pour renvoyer un sous-ensemble de données.

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']
  • Pour de plus amples informations sur l’API, consultez Requête dans la référence d'API AWS du kit SDK pour Python (Boto3).

Ruby
Kit SDK pour Ruby
Astuce

Pour découvrir les étapes de configuration et d’exécution de cet exemple, consultez 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
  • Pour plus d'informations sur l'API, consultez Requête dans la référence d'API AWS SDK for Ruby.

Rust
Kit SDK pour Rust
Note

Cette documentation concerne un kit SDK en prévisualisation préliminaire. Le kit SDK est susceptible d’être modifié et ne doit pas être utilisé en production.

Astuce

Pour découvrir les étapes de configuration et d’exécution de cet exemple, consultez GitHub.

Trouvez les films réalisés au cours de l'année spécifiée.

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())) }
  • Pour de plus amples informations sur l'API, consultez Requête dans la référence d'API du kit AWS SDK pour Rust.

Pour obtenir la liste complète des guides de développementAWS SDK et des exemples de code, consultez Utilisation de DynamoDB avec un kit AWS SDK. Cette rubrique comprend également des informations sur le démarrage et sur les versions précédentes du kit de développement logiciel (SDK).