alt*_*ids 11 python amazon-web-services nosql aws-lambda
我是NoSQL并且使用AWS DynamoDB的新手.我使用python 2.7从AWS Lambda调用它我试图从'order_number'字段中检索一个值.
这是我的表看起来像(只有一个记录.):

主分区键:subscription_id
和我的二级全局索引:order_number

我的设置是否正确?如果给定order_number如何使用python检索记录?
我无法弄清楚这样做的语法.
我试过了
response = table.get_item( Key = {'order_number': myordernumber} )
Run Code Online (Sandbox Code Playgroud)
但我得到:
调用GetItem操作时发生错误(ValidationException):提供的键元素与架构不匹配:ClientError
gar*_*aat 16
DynamoDB不会自动索引对象的所有字段.默认情况下,您可以定义一个哈希键(subscription_id在您的情况下),也可以选择一个范围键,这些键将被索引.所以,你可以这样做:
response = table.get_item(Key={'subscription_id': mysubid})
Run Code Online (Sandbox Code Playgroud)
它将按预期工作.但是,如果要根据需要检索项目,则order_number必须使用scan查看表中所有项目的操作来查找具有正确值的项目.这是一项非常昂贵的操作.或者,您可以在表中创建用order_number作主键的全局二级索引.如果您这样做并调用新索引order_number-index,则可以查询与特定订单号匹配的对象,如下所示:
from boto3.dynamodb.conditions import Key, Attr
response = table.query(
IndexName='order_number-index',
KeyConditionExpression=Key('order_number').eq(myordernumber))
Run Code Online (Sandbox Code Playgroud)
DynamoDB是一个非常快速,可扩展且高效的数据库,但它确实需要考虑您可能想要搜索哪些字段以及如何有效地执行此操作.
好消息是,现在您可以将GSI添加到现有表中.以前你必须删除你的表并重新开始.
use*_*554 10
确保您已导入此内容:
from boto3.dynamodb.conditions import Key, Attr
Run Code Online (Sandbox Code Playgroud)
如果你没有它,你肯定会得到错误.它在文档示例中.
感谢@altoids上面的评论,因为这对我来说是正确的答案.我希望通过"正式"答案引起注意.
使用带过滤器的索引查询 dynamodb:
import boto3
from boto3.dynamodb.conditions import Key, Attr
dynamodb = boto3.resource('dynamodb', region_name=region)
table = dynamodb.Table('<TableName>')
response = table.query(
IndexName='<Index>',
KeyConditionExpression=Key('<key1>').eq('<value>') & Key('<key2>').eq('<value>'),
FilterExpression=Attr('<attr>').eq('<value>')
)
print(response['Items'])
Run Code Online (Sandbox Code Playgroud)
如果不需要过滤器,则不要FilterExpression在查询中使用。
| 归档时间: |
|
| 查看次数: |
21251 次 |
| 最近记录: |