Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch all items of a particular Attribute from an AWS DynamoDB Table using Python boto3?

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.

like image 762
FCoding Avatar asked Dec 18 '22 00:12

FCoding


2 Answers

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']
like image 154
Hagar Tal Avatar answered Dec 27 '22 02:12

Hagar Tal


If you have DynamoDB table 'Test' as follows: enter image description here

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: enter image description here

like image 31
Venkatesh Wadawadagi Avatar answered Dec 27 '22 00:12

Venkatesh Wadawadagi