Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query all items by partition key in Dynamo using boto3

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?

like image 220
Matt Morgan Avatar asked Dec 26 '18 17:12

Matt Morgan


People also ask

Can you query by sort key only DynamoDB?

You can not query only using a Sort Key. You need to specify a partition key to perform query operations. Else, you need to create a global secondary index or perform a scan operation.

Does DynamoDB query return all items?

The Query operation in Amazon DynamoDB finds items based on primary key values. You must provide the name of the partition key attribute and a single value for that attribute. Query returns all items with that partition key value.

Why must a DynamoDB query include a value for the partition key?

Why do I need a partition key? DynamoDB stores data as groups of attributes, known as items. Items are similar to rows or records in other database systems. DynamoDB stores and retrieves each item based on the primary key value, which must be unique.


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)

like image 166
Matt Morgan Avatar answered Oct 13 '22 14:10

Matt Morgan