How to Use Expression Attribute Values in DynamoDB
In DynamoDB, use
ExpressionAttributeValues to safely substitute values in your expressions by defining placeholders like :val mapped to actual values. This helps avoid conflicts with reserved words and injection issues when using condition or update expressions.Syntax
The ExpressionAttributeValues is a map where each key is a placeholder starting with a colon (:), and the value is the actual data you want to use in your expression.
Example placeholders: :val1, :age, :name
These placeholders are then used in expressions like KeyConditionExpression, FilterExpression, or UpdateExpression.
json
ExpressionAttributeValues = {
':val1': {"S": "example"},
':age': {"N": "30"}
}
KeyConditionExpression = 'AttributeName = :val1 AND Age > :age'Example
This example shows how to query a DynamoDB table using ExpressionAttributeValues to safely pass values in the query expression.
python
import boto3 # Create DynamoDB client client = boto3.client('dynamodb') # Query parameters params = { 'TableName': 'Users', 'KeyConditionExpression': 'UserId = :userId', 'ExpressionAttributeValues': { ':userId': {'S': 'user123'} } } # Perform query response = client.query(**params) # Print items print(response.get('Items', []))
Output
[{'UserId': {'S': 'user123'}, 'Name': {'S': 'Alice'}, 'Age': {'N': '29'}}]
Common Pitfalls
- Not prefixing placeholders with a colon (
:) causes syntax errors. - Using reserved words directly in expressions without placeholders leads to errors.
- Forgetting to include all placeholders used in expressions inside
ExpressionAttributeValues. - Mixing up
ExpressionAttributeNames(for attribute keys) andExpressionAttributeValues(for attribute values).
json
Wrong:
ExpressionAttributeValues = {
'userId': {'S': 'user123'} # Missing colon prefix
}
Right:
ExpressionAttributeValues = {
':userId': {'S': 'user123'}
}Quick Reference
| Concept | Description | Example |
|---|---|---|
| Placeholder format | Keys must start with a colon (:) | ":val1" |
| Value types | Use DynamoDB data types like S (string), N (number) | {':age': {'N': '25'}} |
| Usage | Used in expressions to substitute values | KeyConditionExpression: 'Id = :val1' |
| Avoid reserved words | Use ExpressionAttributeNames for attribute keys | ExpressionAttributeNames: {'#n': 'Name'} |
Key Takeaways
Always prefix expression attribute value keys with a colon (:).
Use ExpressionAttributeValues to safely insert values in expressions and avoid reserved word conflicts.
Match every placeholder in your expression with a key in ExpressionAttributeValues.
Remember ExpressionAttributeValues holds values, while ExpressionAttributeNames holds attribute keys.
Use correct DynamoDB data types (S, N, BOOL, etc.) for values in ExpressionAttributeValues.