AWS code-library documentation change
Summary
Added expression attribute names documentation for reserved words/special characters
Security assessment
Addresses syntax requirements rather than security vulnerabilities or protection mechanisms.
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 c249657f1..83ceeb9ed 100644 --- a//code-library/latest/ug/python_3_dynamodb_code_examples.md +++ b//code-library/latest/ug/python_3_dynamodb_code_examples.md @@ -2526,0 +2527,216 @@ Delete the table. +The following code example shows how to compare multiple values with a single attribute in DynamoDB. + + * Use the IN operator to compare multiple values with a single attribute. + + * Compare the IN operator with multiple OR conditions. + + * Understand the performance and expression complexity benefits of using IN. + + + + +**SDK for Python (Boto3)** + + +Compare multiple values with a single attribute using AWS SDK for Python (Boto3). + + + import boto3 + from boto3.dynamodb.conditions import Attr, Key + from typing import Any, Dict, List, Optional + + + def compare_multiple_values( + table_name: str, + attribute_name: str, + values_list: List[Any], + partition_key_name: Optional[str] = None, + partition_key_value: Optional[str] = None, + ) -> Dict[str, Any]: + """ + Query or scan a DynamoDB table to find items where an attribute matches any value from a list. + + This function demonstrates the use of the IN operator to compare a single attribute + against multiple possible values, which is more efficient than using multiple OR conditions. + + Args: + table_name (str): The name of the DynamoDB table. + attribute_name (str): The name of the attribute to compare against the values list. + values_list (List[Any]): List of values to compare the attribute against. + partition_key_name (Optional[str]): The name of the partition key attribute for query operations. + partition_key_value (Optional[str]): The value of the partition key to query. + + Returns: + Dict[str, Any]: The response from DynamoDB containing the matching items. + """ + # Initialize the DynamoDB resource + dynamodb = boto3.resource("dynamodb") + table = dynamodb.Table(table_name) + + # Create the filter expression using the is_in method + filter_expression = Attr(attribute_name).is_in(values_list) + + # If partition key is provided, perform a query operation + if partition_key_name and partition_key_value: + key_condition = Key(partition_key_name).eq(partition_key_value) + response = table.query( + KeyConditionExpression=key_condition, FilterExpression=filter_expression + ) + else: + # Otherwise, perform a scan operation + response = table.scan(FilterExpression=filter_expression) + + # Handle pagination if there are more results + items = response.get("Items", []) + while "LastEvaluatedKey" in response: + if partition_key_name and partition_key_value: + response = table.query( + KeyConditionExpression=key_condition, + FilterExpression=filter_expression, + ExclusiveStartKey=response["LastEvaluatedKey"], + ) + else: + response = table.scan( + FilterExpression=filter_expression, ExclusiveStartKey=response["LastEvaluatedKey"] + ) + items.extend(response.get("Items", [])) + + # Return the complete result + return {"Items": items, "Count": len(items)} + + + def compare_with_or_conditions( + table_name: str, + attribute_name: str, + values_list: List[Any], + partition_key_name: Optional[str] = None, + partition_key_value: Optional[str] = None, + ) -> Dict[str, Any]: + """ + Alternative implementation using multiple OR conditions instead of the IN operator. + + This function is provided for comparison to show why using the IN operator is preferable. + With many values, this approach becomes verbose and less efficient. + + Args: + table_name (str): The name of the DynamoDB table. + attribute_name (str): The name of the attribute to compare against the values list. + values_list (List[Any]): List of values to compare the attribute against. + partition_key_name (Optional[str]): The name of the partition key attribute for query operations. + partition_key_value (Optional[str]): The value of the partition key to query. + + Returns: + Dict[str, Any]: The response from DynamoDB containing the matching items. + """ + # Initialize the DynamoDB resource + dynamodb = boto3.resource("dynamodb") + table = dynamodb.Table(table_name) + + # Create a filter expression with multiple OR conditions + filter_expression = None + for value in values_list: + condition = Attr(attribute_name).eq(value) + if filter_expression is None: + filter_expression = condition + else: + filter_expression = filter_expression | condition + + # If partition key is provided, perform a query operation + if partition_key_name and partition_key_value and filter_expression: + key_condition = Key(partition_key_name).eq(partition_key_value) + response = table.query( + KeyConditionExpression=key_condition, FilterExpression=filter_expression + ) + elif filter_expression: + # Otherwise, perform a scan operation + response = table.scan(FilterExpression=filter_expression) + else: + # Return empty response if no values provided + return {"Items": [], "Count": 0} + + # Handle pagination if there are more results + items = response.get("Items", []) + while "LastEvaluatedKey" in response: + if partition_key_name and partition_key_value: + response = table.query( + KeyConditionExpression=key_condition, + FilterExpression=filter_expression, + ExclusiveStartKey=response["LastEvaluatedKey"], + ) + else: + response = table.scan( + FilterExpression=filter_expression, ExclusiveStartKey=response["LastEvaluatedKey"] + ) + items.extend(response.get("Items", [])) + + # Return the complete result + return {"Items": items, "Count": len(items)} + + + + + +Example usage of comparing multiple values with AWS SDK for Python (Boto3). + + + def example_usage(): + """Example of how to use the compare_multiple_values function.""" + # Example parameters + table_name = "Products" + attribute_name = "Category" + values_list = ["Electronics", "Computers", "Accessories"] + + print(f"Searching for products in any of these categories: {values_list}") + + # Using the IN operator (recommended approach) + print("\nApproach 1: Using the IN operator") + response = compare_multiple_values( + table_name=table_name, attribute_name=attribute_name, values_list=values_list + ) + + print(f"Found {response['Count']} products in the specified categories") + + # Using multiple OR conditions (alternative approach) + print("\nApproach 2: Using multiple OR conditions") + response2 = compare_with_or_conditions( + table_name=table_name, attribute_name=attribute_name, values_list=values_list + ) + + print(f"Found {response2['Count']} products in the specified categories") + + # Example with a query operation + print("\nQuerying a specific manufacturer's products in multiple categories") + partition_key_name = "Manufacturer" + partition_key_value = "Acme" + + response3 = compare_multiple_values( + table_name=table_name, + attribute_name=attribute_name, + values_list=values_list, + partition_key_name=partition_key_name, + partition_key_value=partition_key_value, + ) + + print(f"Found {response3['Count']} Acme products in the specified categories") +