0
votes

I have created a table in DynamoDB that has both a primary key(string) and a sort key(number)(course-lesson-id) and I am using the following simple Lambda function to query the table where the course-lesson-id > 0:

import json
import boto3
from boto3.dynamodb.conditions import Key, Attr

#always start with the lambda_handler
def lambda_handler(event, context):

    # make the connection to dynamodb
    dynamodb = boto3.resource('dynamodb')

    # select the table
    table = dynamodb.Table("table-name")

    response = table.query(
    KeyConditionExpression=Key('course-lesson-id').gt(0)
    )
    items = response['Items']
    print(items)

As I understand it, the results are supposed to be returned in numeric order based on the sort key, but I am getting the following error:

ClientError: An error occurred (ValidationException) when calling the 
Query operation: Query condition missed key schema element: course- 
lesson

course-lesson is the name of the primary partition key.

Any thoughts on possible causes or fixes?

1
It looks like it is returning values sorted by the Key first, then Sort Key.John Rotenstein
Nope, it isnt sorting by the partition key as it isnt used for such when performing a scan.DataGuy

1 Answers

2
votes

You need to provide a primary key for a Query operation. From the Query docs:

Use the KeyConditionExpression parameter to provide a specific value for the partition key. [...] You can optionally narrow the scope of the Query operation by specifying a sort key value [...]

You can't use a Query by only providing a sort key. If you only want to query based on the course-lesson-id filtering for greater than 0, then use a Scan - however, take care that Scans are "more expensive" in terms of resource usage, i.e. for big tables they take a lot longer to execute.