Scanning with the Scan operation - ( DynamoDB Query and Scan Operations )
Syntax:
table.scan(
FilterExpression=Attr('attribute_name').eq('value')
)
Example:
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('users')
response = table.scan(
FilterExpression=Attr('age').gt(20)
)
items = response['Items']
for item in items:
print(item)
Output:
{'name': 'John', 'age': 30, 'email': 'john@email.com'}
{'name': 'Mia', 'age': 23, 'email': 'mia@email.com'}
Explanation:
In DynamoDB, a Scan operation reads all of the items from a table and returns them in a paginated way. This operation is generally slower and less efficient than a Query operation, because it needs to read every item in the table, but can be used when querying on non-key attributes or when the data distribution is not predictable.
The FilterExpression
parameter can be used to filter the results of the scan based on a specific attribute value. Multiple filters can also be applied to narrow down the results. In the example above, we scan the 'users' table and filter the results to only show items where the 'age' attribute is greater than 20.
Use:
The Scan operation can be used when querying on non-key attributes or when the data distribution is not predictable. It can also be useful when requiring the retrieval of all items in a table, as opposed to just a subset.
Important Points:
- The Scan operation reads all items from a table and returns them in a paginated way.
- It is generally slower and less efficient than a Query operation.
- The
FilterExpression
parameter can be used to apply attribute filters to the results. - Multiple filters can be applied to narrow down the results.
Summary:
The Scan operation is used to read all of the items from a table and returns them in a paginated way. It is generally slower and less efficient than a Query operation, but can be useful when querying on non-key attributes or when requiring the retrieval of all items in a table. Filters can be applied to narrow down the results using the FilterExpression
parameter.