JAW
JAW

Reputation: 227

How can I substitute variables for querying DynamoDB attributes?

I am trying to generalize a DynamoDB query using a Python Lambda function. There are numerous examples of ProjectionExpression being set to include the actual values of the attributes in the database, e. g. ProjectionExpression='cats, dogs'. I can't find any examples of the attributes being set in a variable such as below. I want to pass in the values of the attributes to retrieve with the query string event.

attr1 = 'cats'
attr2 = 'dogs'
response = table.query(
    IndexName='pets-index',
    KeyConditionExpression=Key(queryparamKey).eq(queryparamKeyID),
    # Get two attr
    # Does not work
    #ProjectionExpression="attr1, attr2"
    # Neither does this
    #ExpressionAttributeNames='{"#attr1":attr1,"#attr2":attr2}'
)

This is the idea but is for javascript and uses ExpressionAttributeNames.

This can't be all that esoteric, but I am only now encountering Python and I have not found any postings. Please advise.

Upvotes: 3

Views: 1216

Answers (2)

JAW
JAW

Reputation: 227

Through some additional floundering with Python syntax I found this is what works:

ProjectionExpression=attr1+","+attr2

The ProjectionExpression='attr, attr2' was not being evaluated correctly so I got a KeyError when I tried to build a response like:

'body': response['Items'][0][attr1]+"|"+response['Items'][0][attr2]

Hope this saves some other Python newbies some floundering.

Upvotes: 0

Milan Cermak
Milan Cermak

Reputation: 8064

Say if you want to get only attr1 and attr2 from your table using pets-index where the pet_type partition key is cats, this should work:

response = table.query(
    IndexName='pets-index',
    KeyConditionExpression='pet_type = :value',
    ExpressionAttributeValues={
        ':value': {'S': 'cats'}
    },
    ProjectionExpression='attr1,attr2'
)

Upvotes: 1

Related Questions