현재 DynamoDB Table 형태는 아래와 같다.
이 테이블에서 특정 deviceName을 가진 항목(row)를 삭제하려고 했으나, 기본 delete 함수는 partition key와 sort key가 모두 있어야만 했고 하나씩만 삭제할 수 있었다.
그래서 batchWriteItem을 사용해서 여러 항목을 한 번에 삭제했다.
lambda에서 node.js를 사용해서 삭제했다.
// delete raw data
const AWS = require("aws-sdk");
const dynamo = new AWS.DynamoDB.DocumentClient();
const TABLE_NAME = 'test-rawdata-tbl';
const SORT_KEY = 'deleteTime';
exports.handler = async (event) => {
const deviceName = event.deviceName;
const items = await getItems(deviceName);
const params = prepareRequestParams(items.Items, deviceName);
const chunks = await sliceInChunks(params);
const res = await deleteItems(chunks);
return res;
};
async function getItems (deviceName) {
let data = await dynamo
.query({
TableName: "test-rawdata-tbl",
KeyConditionExpression: "deviceName = :dn",
ExpressionAttributeValues: {
":dn": deviceName
},
ScanIndexForward: false // 오름차순
})
.promise();
return data;
}
function prepareRequestParams(items, deviceName) {
const requestParams = items.map((i) => ({
DeleteRequest: {
Key: {
deviceName: deviceName,
deleteTime: i[SORT_KEY],
},
},
}));
return requestParams;
}
async function sliceInChunks(arr) {
let i;
let j;
const CHUNK_SIZE = 25; // DynamoDB BatchWriteItem limit
const chunks = [];
for (i = 0, j = arr.length; i < j; i += CHUNK_SIZE) {
chunks.push(arr.slice(i, i + CHUNK_SIZE));
}
return chunks;
}
async function deleteItems(chunks) {
const promises = chunks.map(async function(chunk) {
const params = {RequestItems: {[TABLE_NAME]: chunk}};
const res = await dynamo.batchWrite(params).promise();
return res;
});
return await Promise.all(promises);
}
https://gist.github.com/rproenca/5b5fbadd38647a40d8be4497fb8aeb8a
https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html