0
0
DynamoDBquery~5 mins

Filter expressions in DynamoDB

Choose your learning style9 modes available
Introduction

Filter expressions help you pick only the items you want from a database query or scan. They act like a sieve, letting through just the data that matches your rules.

When you want to find all products cheaper than $20 in a store's inventory.
When you need to get all users who signed up after a certain date.
When you want to list all orders with status 'shipped'.
When you want to scan a table but only keep items with a specific attribute value.
Syntax
DynamoDB
FilterExpression = "attribute_name operator :value"
ExpressionAttributeValues = {":value": {"S"|"N"|"BOOL"|... : value}}

Example:
FilterExpression = "Price < :maxPrice"
ExpressionAttributeValues = {":maxPrice": {"N": "20"}}

Filter expressions are used with Scan or Query operations in DynamoDB.

They do not reduce the read capacity used; they filter results after reading.

Examples
Find items where the Price attribute is less than 20.
DynamoDB
FilterExpression = "Price < :maxPrice"
ExpressionAttributeValues = {":maxPrice": {"N": "20"}}
Find items where the Category attribute contains the word 'Books'.
DynamoDB
FilterExpression = "contains(Category, :cat)"
ExpressionAttributeValues = {":cat": {"S": "Books"}}
Find items where the Status attribute equals 'shipped'.
DynamoDB
FilterExpression = "Status = :status"
ExpressionAttributeValues = {":status": {"S": "shipped"}}
Sample Program

This command scans the 'Products' table and returns only items where the Price is less than 20. It shows the ProductId and Price for each matching item.

DynamoDB
aws dynamodb scan \
  --table-name Products \
  --filter-expression "Price < :maxPrice" \
  --expression-attribute-values '{":maxPrice":{"N":"20"}}' \
  --projection-expression "ProductId, Price"
OutputSuccess
Important Notes

Filter expressions only filter results after DynamoDB reads the data, so they do not reduce read capacity usage.

Use ExpressionAttributeValues to safely pass values and avoid injection issues.

You can combine multiple conditions using AND, OR, and parentheses in filter expressions.

Summary

Filter expressions help you get only the data you want from a scan or query.

They use simple conditions on attributes like equals, less than, or contains.

Remember, filtering happens after reading, so it does not save read capacity.