【问题标题】:Using both AttributesToGet and KeyConditionExpression with boto3 and dynamodb将 AttributesToGet 和 KeyConditionExpression 与 boto3 和 dynamodb 一起使用
【发布时间】:2022-02-01 03:22:13
【问题描述】:

我有兴趣返回具有给定分区键值(即 u_type = "prospect")的所有记录。但我只想从每条记录中返回特定属性。 我从 boto docs & Stack answers 中收集了以下 sn-p:

resp = table.query(
        Select='SPECIFIC_ATTRIBUTES',
        AttributesToGet=[
            'u_type','ID','action','status','first_name','last_name'
        ],
        KeyConditionExpression=Key('u_type').eq("prospect")
        )

运行时出现以下错误:

An error occurred (ValidationException) when calling the Query operation: 
Can not use both expression and non-expression parameters in the same request: 
Non-expression parameters: {AttributesToGet} 
Expression parameters: {KeyConditionExpression}

此外,我已经尝试使用 ProjectionExpression 和以下实现:

resp = table.query(
        KeyConditionExpression= 'u_type = :hkey',
        ExpressionAttributeValues= {
            ':hkey': "prospect",
        },
        Limit= 200,
        ProjectionExpression= ['u_type','ID','action','status','first_name','last_name']
        )

请注意,这是从为节点编写的another stack overflow answer 调整而来的。

使用此 ProjectionExpression 实现时,我遇到以下错误:

Invalid type for parameter ProjectionExpression, value: 
['u_type', 'ID', 'action', 'status', 'first_name', 'last_name'], type: <class 'list'>, 
valid types: <class 'str'>

我不确定我的方法或描述是否不清楚,但本质上我想使用 boto3 和 dynamo 执行以下 SQL 等效项:

SELECT u_type,ID,action,status,first_name,last_name
FROM table
WHERE u_type LIKE 'prospect';

注意:分区键:u_type,排序键:ID

【问题讨论】:

    标签: python amazon-web-services amazon-dynamodb boto3


    【解决方案1】:

    AttributesToGet 是一个旧参数,the documentation 建议改用较新的ProjectionExpression。该文档还说 ProjectionExpression 是一个字符串,而不是一个列表。在您链接到的答案中,它可能是 NodeJS SDK 中的一个列表,但在 Python 中,文档说它必须是一个字符串。所以我会试试这个:

    resp = table.query(
            KeyConditionExpression= 'u_type = :hkey',
            ExpressionAttributeValues= {
                ':hkey': "prospect",
            },
            Limit= 200,
            ProjectionExpression='u_type,ID,action,status,first_name,last_name'
            )
    

    【讨论】:

    • 工作就像一个魅力!谢谢马克,感谢您的时间!
    猜你喜欢
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 2018-08-17
    • 2022-01-22
    相关资源
    最近更新 更多