Search code examples
amazon-dynamodbboto3

Querying dynamodb with begins_with


How do I query a dynamodb with both dataset_id and an image_name. Using the code below:

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('table_name') 
response = table.query(
           IndexName='dataset_id',
           KeyConditionExpression='dataset_id = :value AND begins_with (image_name, :name)',
           ExpressionAttributeValues={
              ':value': str(dataset_id),
              ':name': {'S', 'a'}
           },
           Limit=int(results_per_page)

This is my dynamodb GSIs.

dymamodb GSIs

What I'm I doing wrong here?

I am expecting the dynamodb response to return images that start with 'a'.


Solution

  • First of all I assume your GSI is called dataset_id and its partition key is dataset_id and its sort key is image_name, if this assumption is false then your use-case is not valid.

    Now to the issue I see, you are using Resource client which uses native JSON not DDB-JSON, so your query should look like this:

    response = table.query(
               IndexName='dataset_id',
               KeyConditionExpression='dataset_id = :value AND begins_with (image_name, :name)',
               ExpressionAttributeValues={
                  ':value': str(dataset_id),
                  ':name': 'a'
               },
               Limit=int(results_per_page))