1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AWS SDK for JavaScript: DynamoDB batchGet/batchWriteのサンプル

Last updated at Posted at 2022-08-20

batchGet は params の構造が覚えづらく、UnprocessedKeysの処理法もやや気を使うのでスニペット。

const AWS = require("aws-sdk");

async function batchPut(tableName, items) {
    const docClient = new AWS.DynamoDB.DocumentClient({ region: "ap-northeast-1" });
    let unprocessedItems = items.slice();
    while (unprocessedItems.length > 0) {
        let limit = 25;
        let batchItems = unprocessedItems.splice(0, limit);
        let params = {
            RequestItems: {
                [tableName]: batchItems.map(item => {
                    return {
                        PutRequest: {
                            Item: item,
                        },
                    };
                }),
            }
        };
        console.log("batchWrite (put)");
        let res = await docClient.batchWrite(params).promise();
        if (res.UnprocessedItems[tableName] != undefined) {
            unprocessedItems = (res.UnprocessedItems[tableName].map(item => item.PutRequest.Item)).concat(unprocessedItems);
        }
    }
}

async function batchDelete(tableName, keys) {
    const docClient = new AWS.DynamoDB.DocumentClient({ region: "ap-northeast-1" });
    let unprocessedItems = keys.slice();
    while (unprocessedItems.length > 0) {
        let limit = 25;
        let batchItems = unprocessedItems.splice(0, limit);
        let params = {
            RequestItems: {
                [tableName]: batchItems.map(key => {
                    return {
                        DeleteRequest: {
                            Key: key,
                        },
                    };
                }),
            }
        };
        console.log("batchWrite (delete)");
        let res = await docClient.batchWrite(params).promise();
        if (res.UnprocessedItems[tableName] != undefined) {
            unprocessedItems = (res.UnprocessedItems[tableName].map(item => item.DeleteRequest.Key)).concat(unprocessedItems);
        }
    }
}

async function batchGet(tableName, keys) {
    const docClient = new AWS.DynamoDB.DocumentClient({ region: "ap-northeast-1" });
    let unprocessedKeys = keys.slice();
    let items = [];
    while (unprocessedKeys.length > 0) {
        let limit = 100;
        let batchKeys = unprocessedKeys.splice(0, limit);
        let params = {
            TableName: tableName,
            RequestItems: {
                [tableName]: {
                    Keys: batchKeys,
                },
            },
        };
        console.log("batchGet");
        let res = await docClient.batchGet(params).promise();
        items = items.concat(res.Responses[tableName]);
        if (res.UnprocessedKeys[tableName] != undefined) {
            unprocessedKeys = res.UnprocessedKeys[tableName].Keys.concat(unprocessedKeys);
        }
    }
    return items;
}

async function main() {
    const TABLE_NAME = "table1";
    const COUNT = 101;

    // サンプルデータを投入。テーブルのプライマリキーはpk (string)
    let putItems = [];
    for (let i = 0; i < COUNT; i++) {
        putItems.push({ pk: i.toString(), val: "*".repeat(1024 * 300) }); // 1アイテム約300KB
    }
    await batchPut(TABLE_NAME, putItems);

    // 投入したデータを全件取得
    let keys = [];
    for (let i = 0; i < COUNT; i++) {
        keys.push({
            pk: i.toString(),
        });
    }
    let items = await batchGet(TABLE_NAME, keys);
    if (items.length == COUNT) {
        console.log("OK");
    } else {
        console.log(`items.length = ${items.length}, COUNT = ${COUNT}`);
    }

    // サンプルデータ削除
    await batchDelete(TABLE_NAME, keys);
}

main();

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?