我是dynamodb的新手,试图从dynamodb获取数据。
This is my table with "topic" as a primary hash key
我的python代码
import boto3
from boto3 import dynamodb
from boto3.session import Session
from boto3.dynamodb.conditions import Key, Attr
dynamodb_session = Session(aws_access_key_id='XXXXXXXXXXXXXXX',
aws_secret_access_key='XXXXXXXXXXXXXXXXXXXXXXXXXXXX',
region_name='us-east-1')
dynamodb = dynamodb_session.resource('dynamodb')
table=dynamodb.Table('Garbage_collector_table')
my_topic = "$aws/things/garbage_collector_thing/shadow/update/accepted"
response = table.get_item(TableName='Garbage_collector_table', Key={'topic':my_topic})
for res in response:
print "result ",res
我收到以下错误
Traceback (most recent call last):
File "get-data-dynamodb-boto3.py", line 19, in <module>
response = table.get_item(TableName='Garbage_collector_table', Key={'topic': my_topic}) File
"/usr/local/lib/python2.7/dist-packages/boto3/resources/factory.py",
line 518, in do_action
response = action(self, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/boto3/resources/action.py",
line 83, in __call__
response = getattr(parent.meta.client, operation_name)(**params) File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line
258, in _api_call
return self._make_api_call(operation_name, kwargs) File /usr/local/lib/python2.7/dist-packages/botocore/client.py", line 548,
in _make_api_call
raise ClientError(parsed_response, operation_name)
botocore.exceptions.ClientError:发生错误 (ValidationException)调用GetItem操作时:提供的 key元素与架构
不匹配
我在代码中遗漏了什么吗?
答案 0 :(得分:9)
正确的语法是:
response = table.get_item(TableName='Garbage_collector_table', Key={'topic':{'S':str(my_topic)}})
但我个人建议使用boto客户端:
client = boto3.client('dynamodb')
response = client.get_item(TableName='Garbage_collector_table', Key={'topic':{'S':str(my_topic)}})
http://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html
答案 1 :(得分:1)
您还可以查询数据库:
from boto3.dynamodb.conditions import Key
table = dynamodb.Table(table_name)
response = table.query(
KeyConditionExpression=Key('topic').eq(my_topic)
)
items = response['Items']
if items:
return item[0]
else:
return []
来源:https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Python.04.html
答案 2 :(得分:1)
我是 Lucid-Dynamodb 的作者,它是 AWS DynamoDB 的极简包装器。使用我的库可以轻松解决此问题。
参考: https://github.com/dineshsonachalam/Lucid-Dynamodb#4-read-an-item
from LucidDynamodb.Operations import DynamoDb
import os
import logging
logging.basicConfig(level=logging.INFO)
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
if __name__ == "__main__":
db = DynamoDb(region_name="us-east-1",
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
item = db.read_item(
TableName="test",
Key={
'topic': "1"
})
if(item != None):
logging.info("Item: {}".format(item))
else:
logging.warning("Item doesn't exist")
答案 3 :(得分:0)
假设您在表中只有分区键(也称为哈希键)。
import boto3
dynamodb = boto3.resource('dynamodb',region_name='ap-southeast-2')
table = dynamodb.Table('my-table')
key = {}
key['key'] = 'my-key'
print(key)
response = table.get_item(Key=key)
print(response['Item'])
答案 4 :(得分:0)
这里有一些实际的例子: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/dynamodb.html
对于您而言,您需要这样做:
response = table.get_item(TableName='Garbage_collector_table', Key={'topic': my_topic})
答案 5 :(得分:0)
如果您还有排序键,则:
dynamodb = boto3.client('dynamodb', region_name=AWS_REGION, aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCCESS_KEY)
response = dynamodb.get_item(
TableName=str(os.environ['DYNAMODB_TABLE']),
Key={'task_id' : {
'S' : str(task_id)
},
'mac' : {
'S' : 'AA-00-04-00-XX-YX'
}
}
)
答案 6 :(得分:-1)
# Have the IAM role containing policy *AmazonDynamoDBFullAccess* assigned to your lambda function
import boto3
def lambda_handler(event, context):
try:
dynamodb_client = boto3.client('dynamodb')
response = dynamodb_client.get_item(
TableName="Garbage_collector_table",
Key={
'topic':
{'S':str(my_topic)}
}
)
except Exception as error:
print(error)
raise
else:
print(f'Response = {response}')
return response