MP32
MP32

Reputation: 721

I don't know how to query certain data from my DynamoDB table using Boto3

This is my first time using boto3 to query items from my DynamoDB and I can't figure out how to grab a certain value.

My table has a primary key of "Company" and a sort key of "DailyPrice". I looked at the boto3 docs and used the example they had and I'm able to return all of the information related to AAPL by searching for that key value.

Here's my python script

import boto3

client = boto3.client('dynamodb')

response = client.query(
    ExpressionAttributeValues={
        ':AAPL': {
            'S': 'AAPL',
        },
    },
    KeyConditionExpression='Company = :AAPL',
    TableName='stock_tracker',
)
number_of_days = response['Count']
items = response['Items']

print(items)

Here's the response

{'Items': [   
    {'Company': {'S': 'AAPL'}, 'DailyPrice': {'S': '142.56'}}, 
    {'Company': {'S': 'AAPL'}, 'DailyPrice': {'S': '154.51'}}, 
    {'Company': {'S': 'AAPL'}, 'DailyPrice': {'S': '156.77'}}], 
'Count': 3, 
'ScannedCount': 3,}

I basically want to grab the daily price of every item for AAPL, because I want to add them all up in a separate python script. I'm not sure how I can grab the daily price specifically using my DynamoDB query

Upvotes: 0

Views: 4222

Answers (1)

hunterhacker
hunterhacker

Reputation: 7132

Your life will be easier with boto3.resource than boto3.client because you don't need all that 'S' type stuff around.

Here's a repo with sample code:

https://github.com/aws-samples/aws-dynamodb-examples/blob/master/DynamoDB-SDK-Examples/python/WorkingWithQueries/query_equals.py

Then just loop over the returned values in Python.

Upvotes: 2

Related Questions