Используя DynamoDB transact_write_items, как выполнить ConditionCheck для существующего элемента и поместить новый элемент, если ConditionCheck имеет значение True?

Я хочу вставить новый элемент в таблицу, только если определенный элемент уже существует. Можно ли добиться этого с помощью transact_write_items? Я хочу избежать запроса таблицы, а затем вставки нового элемента.

response = dynamo_client.transact_write_items(
    TransactItems=[
        {
            'ConditionCheck': {
                'Key': {
                    'indicator_id': {
                        'S': 'indicator_1'
                    }
                },
                'ConditionExpression': 'attribute_exists(#indicator_id)',
                'ExpressionAttributeNames': {
                    '#indicator_id': 'indicator_id'
                },
                'TableName': 'CAS'
            },
            'Put': {
                'Key': {
                    'indicator_id': {
                        'S': 'update_indicator_1'
                    }
                },
                'TableName': 'CAS'
            }
        }
    ]
)

Это вызывает следующую ошибку:

botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the TransactWriteItems operation: TransactItems can only contain one of Check, Put, Update or Delete

person kamaldeep-j    schedule 28.08.2019    source источник


Ответы (2)


В аргументе TransactItems требуется 2 модификации.

Операции в json должны быть перестроены

В операции «Поместить» замените Key на Item.

response = dynamo_client.transact_write_items(
    TransactItems=[
        {
            'ConditionCheck': {
                'Key': {
                    'indicator_id': {
                        'S': 'indicator_1'
                    }
                },
                'ConditionExpression': 'attribute_exists(#indicator_id)',
                'ExpressionAttributeNames': {
                    '#indicator_id': 'indicator_id'
                },
                'TableName': 'CAS'
            }
        },
        {
            'Put': {
                'Item': {
                    'indicator_id': {
                        'S': 'insert_indicator_2'
                    }
                },
                'TableName': 'CAS'
            }
        }
    ]
)

В документации (https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.transact_write_items), хотя все операции упоминаются в том же словаре, но только для справки и следует рассматривать как чек или пут или т. д.

Операции должны быть массивом (списком) таких диктов

person Sajeer Noohukannu    schedule 28.08.2019

Проблема была с синтаксисом.

Правильный синтаксис:

response = dynamo_client.transact_write_items(
    TransactItems=[
        {
            'ConditionCheck': {
                'Key': {
                    'indicator_id': {
                        'S': 'indicator_1'
                    }
                },
                'ConditionExpression': 'attribute_exists(#indicator_id)',
                'ExpressionAttributeNames': {
                    '#indicator_id': 'indicator_id'
                },
                'TableName': 'CAS'
            }
        },
        {
            'Put': {
                'Key': {
                    'indicator_id': {
                        'S': 'update_indicator_1'
                    }
                },
                'TableName': 'CAS'
            }
        }
    ]
)
person kamaldeep-j    schedule 28.08.2019