我想知道是否有一种方法可以选择在dynamodb查询或扫描结果中应包含哪些字段。我尝试使用AttributesToGet
def filter_ga_account_by_email(self, email):
response = Table.scan(
FilterExpression=Attr('client_email').eq(email),
AttributesToGet=['id'],
)
return response['Items']
现在我有这个错误:ClientError: An error occurred (ValidationException) when calling the Scan operation: Can not use both expression and non-expression parameters in the same request: Non-expression parameters: {AttributesToGet} Expression parameters: {FilterExpression}
答案 0 :(得分:1)
确定,
您可以使用' AttributesToGet':
client = boto3.client('dynamodb')
response = client.get_item(TableName='tbl_name', Key={'client_email':{'N':str(email)}}, AttributesToGet=['id'])
但请注意:
这是一个遗留参数,用于向后兼容。新 应用程序应该使用ProjectionExpression。不要结合 单个调用中的遗留参数和表达式参数; 否则,DynamoDB将返回ValidationException异常。这个 参数允许您检索List或Map类型的属性; 但是,它无法检索List或a中的单个元素 地图。
http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html#API_Query_RequestSyntax
答案 1 :(得分:0)
最简单的方法是添加projectionExpression参数并在字符串数组中指定要返回的属性,一个有效的示例:
const getProducts = (user) => {
var params = {
TableName: process.env.PRODUCTS,
ScanIndexForward: false,
KeyConditionExpression: 'user = :hkey',
ExpressionAttributeValues: {
':hkey': user,
},
Limit: 200,
ProjectionExpression: ['internal_type', 'requested_at']
};
return dynamoClient.query(params).promise();
}
答案 2 :(得分:0)
boto3 dynamodb docs 请注意,您不能将 API 的“遗留”部分(包括 Select 和 AttributeToGet 关键字参数)与较新的 API 关键字参数,包括 KeyConditionExpression 和 ProjectionExpression)。这就是您收到 ValidationError 的原因。仅查询某些属性的正确方法是使用 ProjectionExpression
关键字参数。
如果您只想查询特定属性(同时使用“new”关键字参数集),您可以使用以下代码:
import boto3
from boto3.dynamodb.conditions import Key, Attr
table = boto3.resource("dynamodb", region_name='us-east-2').Table(<table_name>
def filter_ga_account_by_email(self, email):
response = table.scan(
IndexName='client_email', # Include if client_email is an indexed field
FilterExpression=Attr('client_email').eq(email), # Include if client_email is a non-indexed field
KeyConditionExpression=Key('client_email').eq(email), # Include if client_email is an indexed field
ProjectionExpression="id", # Comma-separated list of desired attributes, e.g., "id,client_id
)
return response['Items']
针对您关于获取特定属性的问题,ProjectionExpression
是执行此操作的最佳方法。