dynamo-db
  1. dynamo-db-querying-with-the-query-operation

Querying with the Query operation - ( DynamoDB Query and Scan Operations )

Syntax

Querying with the Query operation in DynamoDB has the following syntax:

response = table.query(
    KeyConditionExpression=Key('primary_key').eq('value'),
    FilterExpression=Attr('attribute_name').eq('value'),
    ScanIndexForward=True|False,
    ConsistentRead=True|False
)

Example

Let's assume we have a table named "Movies," with the following attributes:

  • year (partition key - number)
  • title (sort key - string)
  • info (Map)
  • actors (List)
import boto3
from boto3.dynamodb.conditions import Key, Attr

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Movies')

response = table.query(
    KeyConditionExpression=Key('year').eq(1992) & Key('title').begins_with('A'),
    FilterExpression=Attr('info.rating').gt(8),
    ScanIndexForward=False,
    ConsistentRead=True
)

items = response['Items']
for item in items:
    print(item['year'], item['title'])

Output

The above example will output all movies from the year 1992, starting with the letter "A," with a rating greater than 8.

1992 Airborne
1992 Aladdin

Explanation

The query() operation retrieves items from a table or a secondary index.

In the example above, we are using KeyConditionExpression to retrieve all movies from the year 1992 with a title starting with the letter "A."

We are also using FilterExpression to further filter the results to only include items with a rating greater than 8.

The ScanIndexForward parameter specifies whether the results are returned in ascending or descending order. In the example above, we are sorting the results in descending order by setting ScanIndexForward to False.

The ConsistentRead parameter ensures that we are querying against the most up-to-date data in the table.

Use

The query() operation is useful for retrieving specific items from a table or a secondary index based on the primary key and sort key.

It is also useful for filtering the results of a query based on specific attributes.

Important Points

  • query() can retrieve up to 1 MB of data in a single request.
  • You can use KeyConditionExpression to query the table or a secondary index.
  • You can use FilterExpression to further filter the results based on attribute values.
  • You can use ScanIndexForward to specify the sort order of the results.
  • You can use ConsistentRead to ensure that you are querying against the most up-to-date data in the table.

Summary

query() is a powerful operation in DynamoDB that allows you to retrieve specific items from a table or a secondary index based on the primary key and sort key.

You can also use FilterExpression to further filter the results based on specific attribute values.

By setting ScanIndexForward and ConsistentRead, you can customize the behavior of the query() operation to fit your needs.

Published on: