How to Use Contains in DynamoDB: Syntax and Examples
In DynamoDB, use the
contains function in a FilterExpression or ConditionExpression to check if an attribute (like a list or string) contains a specific value. It returns true if the value exists inside the attribute, helping you filter or query items based on partial matches.Syntax
The contains function syntax in DynamoDB is:
contains(path, operand)
Where:
pathis the attribute name you want to check.operandis the value you want to find inside the attribute.
This function returns true if the attribute contains the operand, otherwise false.
sql
FilterExpression: contains(attribute_name, :value)
Example
This example shows how to use contains in a DynamoDB scan operation to find items where the Tags attribute (a list) contains the value "urgent".
python
import boto3 # Create DynamoDB client client = boto3.client('dynamodb') # Scan table with contains filter response = client.scan( TableName='Tasks', FilterExpression='contains(Tags, :tag)', ExpressionAttributeValues={ ':tag': {'S': 'urgent'} } ) # Print matching items for item in response['Items']: print(item)
Output
{'TaskId': {'S': '123'}, 'Description': {'S': 'Fix bug'}, 'Tags': {'L': [{'S': 'urgent'}, {'S': 'backend'}]}}
{'TaskId': {'S': '456'}, 'Description': {'S': 'Write docs'}, 'Tags': {'L': [{'S': 'urgent'}, {'S': 'docs'}]}}
Common Pitfalls
Common mistakes when using contains include:
- Using
containson attributes that are not lists or strings, which will cause errors. - Confusing
containswith equality;containschecks for partial presence, not exact match. - Not defining
ExpressionAttributeValuescorrectly, leading to syntax errors.
Always ensure the attribute type supports contains and that your placeholders are properly set.
sql
Wrong: FilterExpression='contains(Status, :val)' ExpressionAttributeValues={':val': {'S': 'active'}} # if Status is a number, this fails Right: FilterExpression='contains(Status, :val)' ExpressionAttributeValues={':val': {'N': '1'}} # if Status is a number list
Quick Reference
| Function | Description | Usage Example |
|---|---|---|
| contains(path, operand) | Checks if attribute contains operand | contains(Tags, :tag) |
| begins_with(path, substr) | Checks if attribute starts with substring | begins_with(Name, :prefix) |
| attribute_exists(path) | Checks if attribute exists | attribute_exists(Email) |
| attribute_not_exists(path) | Checks if attribute does not exist | attribute_not_exists(DeletedAt) |
Key Takeaways
Use contains() in FilterExpression or ConditionExpression to check if an attribute includes a value.
Contains works on string or list attributes, not on numbers or maps directly.
Always provide ExpressionAttributeValues with correct data types for the operand.
Contains helps filter items by partial matches inside attributes.
Check attribute types before using contains to avoid runtime errors.