Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a ProjectionExpression with reserved words with Boto3 in DynamoDB

Tags:

I'm selecting data from my DynamoDB database using boto3

dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(table_name) response = table.scan(ProjectionExpression='Id,Name')['Items'] 

Works fine. Now I also want to retrieve an attribute that is (unfortunately) named with a reserved word - let's say CONNECTION.

response = table.scan(ProjectionExpression='Id,Name,Connection')['Items'] 

I get an error like

An error occurred (ValidationException) when calling the Scan operation: Invalid ProjectionExpression: Attribute name is a reserved keyword; reserved keyword: Connection

I know there's an aliasing technique if using filters or queries, but does this exist for simple projections from boto3?

like image 568
Kirk Broadhurst Avatar asked Oct 25 '18 17:10

Kirk Broadhurst


People also ask

How do you use reserved words in DynamoDB?

If you need to write an expression containing an attribute name that conflicts with a DynamoDB reserved word, you can define an expression attribute name to use in the place of the reserved word. For more information, see Expression attribute names in DynamoDB.

What is Projectionexpression DynamoDB?

Amazon DynamoDB returns all the item attributes by default. To get only some, rather than all of the attributes, use a projection expression. A projection expression is a string that identifies the attributes that you want. To retrieve a single attribute, specify its name.

What is Expressionattributenames in DynamoDB?

An expression attribute name is a placeholder that you use in an Amazon DynamoDB expression as an alternative to an actual attribute name. An expression attribute name must begin with a pound sign ( # ), and be followed by one or more alphanumeric characters.

How does Python connect to DynamoDB?

Connecting AWS resources to the python environment requires a boto3 package. Creating a dynamo DB client is a connection instance that lets us connect with our dynamo DB service. We need to specify region_name , aws_access_key_id , aws_secret_access_key in order to connect with our dynamoDb service.


1 Answers

Turns out that this is easily solved the same as when calling the DynamoDB API directly.

We should use an alias for any reserved word, and then provide a mapping from the alias back to the 'true' name with the ExpressionAttributeName parameter/property.

response = table.scan(ProjectionExpression = 'Id, Name, #c',                       ExpressionAttributeNames = {'#c': 'Connection'})['Items'] 
like image 65
Kirk Broadhurst Avatar answered Sep 21 '22 15:09

Kirk Broadhurst