[英]How to fetch all items of a particular Attribute from an AWS DynamoDB Table using Python boto3?
我對AWS Dynamodb相當陌生。 我正在使用python的boto3從dynamodb表中獲取特定屬性的所有項目(例如,屬性名稱為“名稱”)。
盡管表中還有其他屬性,例如“電子郵件”,“專業”。 我只需要獲取或獲取屬性“名稱”的所有項目。 我的名字屬性包含四個項目:尼克,約翰,加里,朱爾斯。 我如何使用boto3獲取此內容? 我嘗試使用boto3的client.query方法,但是不確定是否可以使用。
假設“ User
是表名,您僅希望從中獲取“ NAME
屬性。 首先掃描表並對其進行遍歷,並獲得NAME
屬性並存儲在列表中。 在這里,我將NAME
屬性的值存儲在名為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
要獲取屬性為“名稱”的所有項目,請使用以下代碼:
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'))
不知道答案是否晚了,但是您可以使用“ ProjectionExpression”之類的東西從Dynamodb中獲取name屬性:例如,在您的情況下,您應該使用諸如
tableparam = { 'ProjectionExpression':"Name" }
reponse = tablename.scan(**tableparams)
它為我工作。 讓我知道是否有幫助。
您可以在使用“掃描”功能時使用AttributesToGet。
import boto3
import json
def getNames():
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('User')
response = table.scan(AttributesToGet=['name'])
return response['Items']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.