AWS code-library documentation change
Summary
Added date/time query patterns with ISO 8601 formatting and range examples
Security assessment
Focuses on temporal query techniques without any security context or protective measures mentioned
Diff
diff --git a/code-library/latest/ug/python_3_dynamodb_code_examples.md b/code-library/latest/ug/python_3_dynamodb_code_examples.md index acf01f25c..c8851f869 100644 --- a//code-library/latest/ug/python_3_dynamodb_code_examples.md +++ b//code-library/latest/ug/python_3_dynamodb_code_examples.md @@ -1695 +1695 @@ The following code example shows how to use `Query`. -**SDK for Python (Boto3)** + * Use the begins_with function in a key condition expression. @@ -1696,0 +1697 @@ The following code example shows how to use `Query`. + * Filter items based on a prefix pattern in the sort key. @@ -1698 +1698,0 @@ The following code example shows how to use `Query`. -###### Note @@ -1700 +1699,0 @@ The following code example shows how to use `Query`. -There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples). @@ -1702 +1700,0 @@ There's more on GitHub. Find the complete example and learn how to set up and ru -Query items by using a key condition expression. @@ -1703,0 +1702 @@ Query items by using a key condition expression. +**SDK for Python (Boto3)** @@ -1705,2 +1703,0 @@ Query items by using a key condition expression. - class Movies: - """Encapsulates an Amazon DynamoDB table of movie data. @@ -1708,19 +1705 @@ Query items by using a key condition expression. - Example data structure for a movie record in this table: - { - "year": 1999, - "title": "For Love of the Game", - "info": { - "directors": ["Sam Raimi"], - "release_date": "1999-09-15T00:00:00Z", - "rating": 6.3, - "plot": "A washed up pitcher flashes through his career.", - "rank": 4987, - "running_time_secs": 8220, - "actors": [ - "Kevin Costner", - "Kelly Preston", - "John C. Reilly" - ] - } - } - """ +Query a DynamoDB table using a begins_with condition on the sort key with AWS SDK for Python (Boto3). @@ -1728,8 +1706,0 @@ Query items by using a key condition expression. - 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 @@ -1736,0 +1708,2 @@ Query items by using a key condition expression. + import boto3 + from boto3.dynamodb.conditions import Key @@ -1738,3 +1710,0 @@ Query items by using a key condition expression. - def query_movies(self, year): - """ - Queries for movies that were released in the specified year. @@ -1742,2 +1712,3 @@ Query items by using a key condition expression. - :param year: The year to query. - :return: The list of movies that were released in the specified year. + def query_with_begins_with( + table_name, partition_key_name, partition_key_value, sort_key_name, prefix + ): @@ -1745,12 +1716 @@ Query items by using a key condition expression. - 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"] + Query a DynamoDB table with a begins_with condition on the sort key. @@ -1757,0 +1718,6 @@ Query items by using a key condition expression. + Args: + table_name (str): The name of the DynamoDB table. + partition_key_name (str): The name of the partition key attribute. + partition_key_value (str): The value of the partition key to query. + sort_key_name (str): The name of the sort key attribute. + prefix (str): The prefix to match at the beginning of the sort key. @@ -1758,0 +1725,6 @@ Query items by using a key condition expression. + Returns: + dict: The response from DynamoDB containing the query results. + """ + # Initialize the DynamoDB resource + dynamodb = boto3.resource("dynamodb") + table = dynamodb.Table(table_name) @@ -1759,0 +1732,5 @@ Query items by using a key condition expression. + # Perform the query with a begins_with condition on the sort key + key_condition = Key(partition_key_name).eq(partition_key_value) & Key( + sort_key_name + ).begins_with(prefix) + response = table.query(KeyConditionExpression=key_condition) @@ -1761 +1738 @@ Query items by using a key condition expression. -Query items and project them to return a subset of data. + return response @@ -1764,43 +1740,0 @@ Query items and project them to return a subset of data. - 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"] - @@ -2678,2 +2611,0 @@ Create DynamoDB table with warm throughput setting using AWS SDK for Python (Bot - from cgitb import reset - @@ -2908,0 +2841,419 @@ The following code example shows how to create an item with TTL. +The following code example shows how to perform advanced query operations in DynamoDB. + + * Query tables using various filtering and condition techniques. + + * Implement pagination for large result sets. + + * Use Global Secondary Indexes for alternate access patterns. + + * Apply consistency controls based on application requirements. + + + + +**SDK for Python (Boto3)** + + +Query with strongly consistent reads using AWS SDK for Python (Boto3). + + + import time + + import boto3 + from boto3.dynamodb.conditions import Key + + + def query_with_consistent_read( + table_name, + partition_key_name, + partition_key_value, + sort_key_name=None, + sort_key_value=None, + consistent_read=True, + ): + """ + Query a DynamoDB table with the option for strongly consistent reads. + + Args: + table_name (str): The name of the DynamoDB table. + partition_key_name (str): The name of the partition key attribute. + partition_key_value (str): The value of the partition key to query. + sort_key_name (str, optional): The name of the sort key attribute. + sort_key_value (str, optional): The value of the sort key to query. + consistent_read (bool, optional): Whether to use strongly consistent reads. Defaults to True. + + Returns: + dict: The response from DynamoDB containing the query results. + """ + # Initialize the DynamoDB resource + dynamodb = boto3.resource("dynamodb") + table = dynamodb.Table(table_name) + + # Build the key condition expression