[英]aws cli dynamo db (ValidationException) Error
我正在尋找使用 python 的 boto3 模塊向 dynamodb 批量寫入項目,我得到了這個。 這是我第一次使用 aws cli 或 boto3。 文檔說當存在空值和可能不正確的數據類型時會發生驗證異常錯誤,但我已經玩過所有這些並且它似乎不起作用。
dynamodb 是否只喜歡一次寫入 25 個項目? 如果是這樣,我如何控制這些批次?
我的要求:
client = boto3.client('dynamodb')
response = client.batch_write_item(RequestItems=batch_dict)
batch_dict 的頂部:
{'scraper_exact_urls': [{'PutRequest': {'Item': {'Sku': {'S': 'T104P3'},
'pps_id': {'N': '427285976'},
'scraper_class_name': {'S': 'scraper_class_name'},
'store_id': {'N': '1197386754'},
'updated_by': {'S': 'user'},
'updated_on': {'N': '1480714223'},
'updated_url': {'S': 'http://www.blah.com'}}}},
{'PutRequest': {'Item': {'Sku': {'S': 'T104P3'},
'pps_id': {'N': '427285976'},
'scraper_class_name': {'S': 'scraper_class_name'},
'store_id': {'N': '1197386754'},
'updated_by': {'S': 'user'},
'updated_on': {'N': '1480714223'},
'updated_url': {'S': 'http://www.blah.com'}}}},....
架構:
屬性:“pps_id”=>\\Aws\\DynamoDb\\Enum\\Type::NUMBER、“sku”=>\\Aws\\DynamoDb\\Enum\\Type::STRING、“scraper_class_name”=>\\Aws\\DynamoDb\\Enum\\Type: :STRING, "store_id"=>\\Aws\\DynamoDb\\Enum\\Type::NUMBER, "updated_url"=>\\Aws\\DynamoDb\\Enum\\Type::STRING, "updated_by"=>\\Aws\\DynamoDb\\Enum\\Type ::STRING, "updated_on"=>\\Aws\\DynamoDb\\Enum\\Type::NUMBER, 字段: "pps_id", "scraper_class_name",
錯誤:
ClientError: An error occurred (ValidationException) when calling the BatchWriteItem operation: 1 validation error detected: Value .... Map value must satisfy constraint: [Member must have length less than or equal to 25, Member must have length greater than or equal to 1]
BatchWriteItem API 一次處理 25 個項目。 您可以使用以下改編自非復制批處理問題的代碼,在 25 個項目塊上調用 BatchWriteItem
def batch(iterable, n=1):
l = len(iterable)
for ndx in range(0, l, n):
yield iterable[ndx:min(ndx + n, l)]
client = boto3.client('dynamodb')
for x in batch(batch_dict['scraper_exact_urls'], 25):
subbatch_dict = {'scraper_exact_urls': x}
response = client.batch_write_item(RequestItems=subbatch_dict)
這是批量寫入/刪除許多項目的 Javascript 版本,以防有人需要它:
const batchWriteManyItems = async (tableName, itemObjs, chunkSize = 25) => {
const buildParams = (table) => JSON.parse(`{"RequestItems": {"${table}": []}}`)
const queryChunk = (arr, size) => {
const tempArr = []
for (let i = 0, len = arr.length; i < len; i += size) {
tempArr.push(arr.slice(i, i + size));
}
return tempArr
}
await Promise.all(queryChunk(itemObjs, chunkSize).map(async chunk => {
let itemParams = buildParams(tableName);
itemParams.RequestItems[tableName] = chunk
await dynamoDB.batchWriteItem(itemParams).promise()
}))
}
注意:itemObjs 屬性可以將{PutRequest: {Item: ...}
用於寫入項目和{DeleteRequest: {Item: ...}
用於刪除項目
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.