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?
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.
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 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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With