Home > Net >  How to use ProjectExpression with column names with spaces?
How to use ProjectExpression with column names with spaces?

Time:11-02

I did a big no no and created a large table which included spaces in the names of the columns. I am trying to scan over this table and select particular pieces of information.

    import boto3
    from boto3.dynamodb.conditions import Key

    dynamodb = boto3.resource('dynamodb',
                              region_name='xx-xxxx-xx')
    table = dynamodb.Table('ourtable')

    scan_kwargs = {
        'FilterExpression': Key('primarykey').between(*key_range)
        'ProjectionExpression': "primarykey, other column"
    }

    done = False
    start_key = None
    while not done:
        if start_key:
            scan_kwargs['ExclusiveStartKey'] = start_key
        response = table.scan(**scan_kwargs)
        start_key = response.get('LastEvaluatedKey', None)
        done = start_key is None

Running this gives me this error:

An error occurred (ValidationException) when calling the Scan operation: Invalid ProjectionExpression: Syntax error; token: "column", near: "other column"

I am assuming this is some parsing issues. I have tried a couple of ways of escaping the space to no avail. Those attempts include:

{other column}
\'other column\'
\"other column\"
other column
other\column
other{BEASPACE}column

I would prefer to not remake this table. Thanks for the help in advance.

CodePudding user response:

In DynamoDB expressions, instead of "escaping" column names with quotes or backslashes like you tried, what you need to do is to use references to names listed in an additional ExpressionAttributeNames parameter. For example,

scan_kwargs = {
    'FilterExpression': Key('primarykey').between(*key_range)
    'ProjectionExpression': "primarykey, #othercolumn"
    'ExpressionAttributeNames': {'#othercolumn': 'other column'}
}

Note how in the projection expression I used the reference #othercolumn instead of the column's real name, and then defined that real name (which may contain spaces or other special characters) in the ExpressionAttributeNames.

This feature is documented here: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ExpressionAttributeNames.html

  • Related