0
0
DynamodbHow-ToBeginner ยท 4 min read

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) and ExpressionAttributeValues (for attribute values).
json
Wrong:
ExpressionAttributeValues = {
  'userId': {'S': 'user123'}  # Missing colon prefix
}

Right:
ExpressionAttributeValues = {
  ':userId': {'S': 'user123'}
}
๐Ÿ“Š

Quick Reference

ConceptDescriptionExample
Placeholder formatKeys must start with a colon (:)":val1"
Value typesUse DynamoDB data types like S (string), N (number){':age': {'N': '25'}}
UsageUsed in expressions to substitute valuesKeyConditionExpression: 'Id = :val1'
Avoid reserved wordsUse ExpressionAttributeNames for attribute keysExpressionAttributeNames: {'#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.