0
0
DynamodbHow-ToBeginner ยท 3 min read

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:

  • path is the attribute name you want to check.
  • operand is 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 contains on attributes that are not lists or strings, which will cause errors.
  • Confusing contains with equality; contains checks for partial presence, not exact match.
  • Not defining ExpressionAttributeValues correctly, 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

FunctionDescriptionUsage Example
contains(path, operand)Checks if attribute contains operandcontains(Tags, :tag)
begins_with(path, substr)Checks if attribute starts with substringbegins_with(Name, :prefix)
attribute_exists(path)Checks if attribute existsattribute_exists(Email)
attribute_not_exists(path)Checks if attribute does not existattribute_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.