简体   繁体   中英

Using both AttributesToGet and KeyConditionExpression with boto3 and dynamodb

I am interested in returning all records with a given partition key value (ie, u_type = "prospect"). But I only want to return specific attributes from each of those records. I have scraped together the following snippet from boto docs & Stack answers:

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

When running this I get the following error:

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}

Additionally, I have experimented with using ProjectionExpression with the following implementation:

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

Note that this was adjusted from another stack overflow answer written for node.

When using this ProjectionExpression implementation I face the following error:

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

I am unsure if my approach or description is unclear, but in essence I would like to do the following SQL equivalent using boto3 and dynamo:

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

Note: Partition key: u_type, Sort key: ID

AttributesToGet is a legacy parameter, and the documentation suggests using the newer ProjectionExpression instead. The documentation also says that ProjectionExpression is a string, not a list. It may be a list in the NodeJS SDK, in the answer you linked to, but in Python the documentation says it must be a string. So I would try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM