简体   繁体   中英

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.

Let's assume User is table name from where you want to fetch only NAME attribute. First scan the table and iterate over it and get NAME attribute and store in a list. Here I store the values of NAME attribute in a list named nameList

import boto3
import json

def getNames():
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('User')
    response = table.scan()

    nameList = []
    for i in response['Items']:
        nameList.append(i['NAME'])

    return nameList

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: 在此处输入图片说明

Not sure if it is late to answer but you can use something like "ProjectionExpression" to get just the name attribute from Dynamodb : For example in your case you should use something like

tableparam = { 'ProjectionExpression':"Name" }

reponse = tablename.scan(**tableparams)

It worked for me. Let me know if it helps you.

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM