I am pretty new to AWS Dynamodb. I am using python's boto3 to fetch all items of a particular attribute (say, Attribute name is 'Name') from the dynamodb table.
Although there are other attributes too in the table like 'Email', 'Profession'. I need to fetch or get all items only of the attribute 'Name'. My Name attribute consists of four items : Nick, John, Gary, Jules. How can I fetch this using boto3 ? I tried with client.query method of boto3 but I am not sure if it works.
you can use AttributesToGet when you use the 'scan' function.
import boto3
import json
def getNames():
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('User')
response = table.scan(AttributesToGet=['name'])
return response['Items']
If you have DynamoDB table 'Test' as follows:
To fetch all items with attribute 'Name', use the following code:
from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)
# us-east-1 is the region name here
dynamodb = boto3.resource('dynamodb', 'us-east-1')
# Test is the table name here
table = dynamodb.Table('Test')
# Table scan
response = table.scan()
for i in response['Items']:
# get all the table entries in json format
json_str = json.dumps(i, cls=DecimalEncoder)
#using json.loads will turn your data into a python dictionary
resp_dict = json.loads(json_str)
# Getting particular column entries
# will return None if 'Name' doesn't exist
print (resp_dict.get('Name'))
Sample output:
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