Home > Software design >  How to update count in dynamo table with 2 fields
How to update count in dynamo table with 2 fields

Time:01-10

The Dynamodb table has 1 partition key and 2 fields. I'm trying to increment a or b by 1.

I get cur_count for a or b(which is 0) from the table and 1 to it.

The error:

An error occurred (ValidationException) 

When calling the UpdateItem operation:

Invalid UpdateExpression: Syntax error; token: "=", near: "#a =#cur_count"

io

def update_count(vote):
    logging.info('update count....')
    print('update count....')
    print('vote'   str(vote))
    '''
    table.update_item(
    Key={'voter': 'count'},
    UpdateExpression="ADD #vote :incr",
    ExpressionAttributeNames={'#vote': vote},
    ExpressionAttributeValues={':incr': 1}
    )
    '''
    cur_count = 0
    try:
        if vote == 'b':
            print('extracting cur count for b')
            q = table.get_item(Key={'voter':'count'})
            res = q['Item']
            print(res)
            cur_count = int(res['b'])
            print('****** cur count %d ' % cur_count)
            cur_count = str(cur_count)
            table.update_item(
                    Key={'voter':'count'},
                    UpdateExpression="ADD #b =#cur_count   :incr",
                    ExpressionAttributeNames={'#cur_count': cur_count},
                    ExpressionAttributeValues={':incr': 1})
            print('******* b %d ' % b)
        elif vote == 'a':
            print('extracting cur count for a')
            q = table.get_item(Key={'voter':'count'})
            res = q['Item']
            print(res)
            cur_count = int(res['a'])
            print('****** cur count %d ' % cur_count)
            cur_count = str(cur_count)

            table.update_item(
                    Key={'voter':'count'},
                    UpdateExpression="ADD #a =#cur_count   :incr",
                    ExpressionAttributeNames={'#cur_count': cur_count},
                    ExpressionAttributeValues={':incr': 1})
            print('***** a %d ' % a)
    except Exception as e:
        print('catching error here')
        print(e)

CodePudding user response:

You define #a or #b as column name expressions but there is no mapping for this columns.

There are two options to fix this issue.

table.update_item(
    Key={'voter':'count'},
    UpdateExpression="ADD #column :incr",
    ExpressionAttributeNames={'#column': 'b'},
    ExpressionAttributeValues={':incr': 1}
)

or

table.update_item(
    Key={'voter':'count'},
    UpdateExpression="ADD b :incr",
    ExpressionAttributeValues={':incr': 1}
)
  • Related