Query all items by partition key in Dynamo using boto3

Viewed 10261

I have a table in DynamoDB with both partition and sort keys. I want to retrieve all the items that have a given partition key, regardless of the sort key.

How do I do this?

1 Answers

The following approach will work both for tables with partition keys only, and for tables with partition and sort keys:

from boto3 import resource
from boto3.dynamodb.conditions import Key


dynamodb_resource = resource('dynamodb')

def query_table(table_name, key=None, value=None):
    table = dynamodb_resource.Table(table_name)

    if key is not None and value is not None:
        filtering_exp = Key(key).eq(value)
        return table.query(KeyConditionExpression=filtering_exp)

    raise ValueError('Parameters missing or invalid')

if __name__ == '__main__':
    resp = query_table(
        table_name='my-table', 
        key='key-name', 
        value='match-me'
    )
    items = resp.get('Items')
    print(len(items))

Note: I originally found a helpful answer for this here. Credit where credit is due! (link updated 8/21)

Related