How to Use Expression Attribute Names in DynamoDB
In DynamoDB, use
ExpressionAttributeNames to replace reserved words or special characters in your expressions by mapping placeholders (like #name) to actual attribute names. This lets you safely write queries or updates without syntax errors caused by reserved keywords.Syntax
The ExpressionAttributeNames is a map where keys are placeholders starting with # and values are the actual attribute names you want to use in your expression. You then use these placeholders in your KeyConditionExpression, FilterExpression, or UpdateExpression.
Example parts:
ExpressionAttributeNames: { "#attr": "actualAttributeName" }KeyConditionExpression: "#attr = :value"
json
ExpressionAttributeNames = {
"#attr": "actualAttributeName"
}
KeyConditionExpression = "#attr = :value"Example
This example shows how to query a DynamoDB table where the attribute name is a reserved word like Year. We use ExpressionAttributeNames to map #yr to Year and then use #yr in the query expression.
python
import boto3 # Initialize DynamoDB client client = boto3.client('dynamodb') table_name = 'Movies' response = client.query( TableName=table_name, KeyConditionExpression='#yr = :year', ExpressionAttributeNames={ '#yr': 'Year' }, ExpressionAttributeValues={ ':year': {'N': '2015'} } ) print(response['Items'])
Output
[{'Year': {'N': '2015'}, 'Title': {'S': 'The Big New Movie'}}]
Common Pitfalls
Common mistakes include:
- Not using
ExpressionAttributeNameswhen your attribute name is a reserved word, causing syntax errors. - Forgetting to prefix placeholders with
#in expressions. - Using the actual attribute name directly in expressions instead of the placeholder.
Always map reserved or special attribute names to placeholders and use those placeholders in your expressions.
text
Wrong: KeyConditionExpression = "Year = :year" # 'Year' is reserved, causes error Right: KeyConditionExpression = "#yr = :year" ExpressionAttributeNames = {"#yr": "Year"}
Quick Reference
| Concept | Description | Example |
|---|---|---|
| ExpressionAttributeNames | Map placeholders to actual attribute names | {"#name": "Name"} |
| Placeholder | Use in expressions instead of attribute names | #name = :val |
| When to use | Reserved words or special characters in attribute names | Year, Size, Status |
| Prefix | Placeholders must start with # | #attr |
| Expression types | Used in KeyCondition, Filter, Update expressions | KeyConditionExpression, FilterExpression |
Key Takeaways
Use ExpressionAttributeNames to avoid conflicts with reserved words in DynamoDB expressions.
Always prefix attribute name placeholders with # and map them in ExpressionAttributeNames.
Never use reserved words directly in expressions; always use placeholders.
ExpressionAttributeNames works with KeyConditionExpression, FilterExpression, and UpdateExpression.
Check DynamoDB reserved words list if you get syntax errors referencing attribute names.