使用可选参数扫描 dynamodb
Scanning dynamodb with optional parameters
我是 dynamodb 的新手,我正在尝试创建一个函数来扫描 table 并有一个可选参数,但我不太确定如何实现它。这是我到目前为止的代码:
def scan_table(table, store=None, dynamodb=None):
if not dynamodb:
dynamodb = boto3.resource('dynamodb')
response = table.scan()
data = response['Items']
while 'LastEvaluatedKey' in response:
response = table.scan(
FilterExpression=Key('store').eq(store),
ExclusiveStartKey=response['LastEvaluatedKey'],
ProjectionExpression="UID, #name, description",
ExpressionAttributeNames={'#name': 'name'}
)
data.extend(response['Items'])
return data
所以理想情况下,我希望发生的事情是,如果我路过一家商店,例如 "walmart"
我只从沃尔玛购买产品。但是,如果我没有通过任何测试,我将获得整个 table 中的所有产品。我怎样才能以优雅的方式做到这一点。
您应该在过滤器表达式中使用 Attribute
而不是 Key
。
FilterExpression (condition from boto3.dynamodb.conditions.Attr method) -- The condition(s) an attribute(s) must meet. Valid conditions are listed in the DynamoDB Reference Guide.
请参阅此文档以获取更多信息:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Table.scan
此外,我建议您为 store
列创建一个 GSI,因为这样您就可以在需要时查询它(我想)。因此,它可以在 RCU 成本方面为您节省更多,并且不会影响 table.
的整体性能
我是 dynamodb 的新手,我正在尝试创建一个函数来扫描 table 并有一个可选参数,但我不太确定如何实现它。这是我到目前为止的代码:
def scan_table(table, store=None, dynamodb=None):
if not dynamodb:
dynamodb = boto3.resource('dynamodb')
response = table.scan()
data = response['Items']
while 'LastEvaluatedKey' in response:
response = table.scan(
FilterExpression=Key('store').eq(store),
ExclusiveStartKey=response['LastEvaluatedKey'],
ProjectionExpression="UID, #name, description",
ExpressionAttributeNames={'#name': 'name'}
)
data.extend(response['Items'])
return data
所以理想情况下,我希望发生的事情是,如果我路过一家商店,例如 "walmart"
我只从沃尔玛购买产品。但是,如果我没有通过任何测试,我将获得整个 table 中的所有产品。我怎样才能以优雅的方式做到这一点。
您应该在过滤器表达式中使用 Attribute
而不是 Key
。
FilterExpression (condition from boto3.dynamodb.conditions.Attr method) -- The condition(s) an attribute(s) must meet. Valid conditions are listed in the DynamoDB Reference Guide.
请参阅此文档以获取更多信息: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Table.scan
此外,我建议您为 store
列创建一个 GSI,因为这样您就可以在需要时查询它(我想)。因此,它可以在 RCU 成本方面为您节省更多,并且不会影响 table.