вставка или обновление динамо в зависимости от условия boto3 - PullRequest
1 голос
/ 25 апреля 2020

У меня есть структура таблицы динамо:

partKey     sortKey         thirdAttribute
1           sort1               x
2           sort2               y
1           sort2               w
2           sort3               z

. Вот как я хочу вставить или обновить:

вставить, если комбинация partition + sortKey не существует

обновлять, только если:

комбинация partition + sortKey существует, но thirdAttribute = x или y, если новый элемент выглядит следующим образом:

item:{
    "partKey":1,
    "sortKey":"sort1",
    "thirdAttribute":"k"
}

или

item:{
    "partKey":2,
    "sortKey":"sort2",
    "thirdAttribute":"l"
}

и новая таблица должна выглядеть следующим образом:

partKey     sortKey         thirdAttribute
1           sort1               k(updated)
2           sort2               l(updated)
1           sort2               w
2           sort3               z
2           sort4               k (inserted)

пробовал с ниже, но не работает, как ожидалось:

table.put_item(
        Item=item,
        ConditionExpression='partKey <> :v_partKey AND sortKey <>:v_sortKey and (attribute_not_exists(thirdAttribute) '
                            'or thirdAttribute <> :v_thirdAttribute_x or thirdAttribute <> :v_thirdAttribute_y)',
    ExpressionAttributeValues={':v_partKey': item['partKey'], ':v_apId': item['sortKey'], ':v_thirdAttribute_x': 'x',':v_thirdAttribute_y':'y'}

1 Ответ

1 голос
/ 25 апреля 2020

Это должно работать:

table.put_item(
        Item=json_data,
        ConditionExpression='(attribute_not_exists(partKey) and attribute_not_exists(sortKey)) or (thirdAttribute <> :v_thirdAttribute_x or thirdAttribute <> :v_thirdAttribute_y)',
    ExpressionAttributeValues={':v_thirdAttribute_x': 'x',
                               ':v_thirdAttribute_y': 'y'}
    )
...