곰돌푸우❤️

목차

    이 글에서는 MusicChart라는 테이블을 생성하겠습니다.
    속성은 아래와 같습니다.

    • company : 파티션 키
    • rank : 정렬 키

    테이블

    테이블 생성

    • company(파티션 키)와, rank(정렬 키) 속성을 포함하여 생성합니다.
    var params = {
        TableName: 'MusicChart',
        KeySchema: [
            { // Required
                AttributeName: 'company',
                KeyType: 'HASH',
            },
            { // Optional
                AttributeName: 'rank', 
                KeyType: 'RANGE', 
            }
        ],
        AttributeDefinitions: [
            {
                AttributeName: 'company',
                AttributeType: 'N', // (S | N | B) for string, number, binary
            },
            {
                AttributeName: 'rank',
                AttributeType: 'N', // (S | N | B) for string, number, binary
            }
        ],
        ProvisionedThroughput: { // required provisioned throughput for the table
            ReadCapacityUnits: 1, 
            WriteCapacityUnits: 1, 
        }
    };
    dynamodb.createTable(params, function(err, data) {
        if (err) {
            console.log(err); // an error occurred
        } else {
            console.log(data); // successful response
        }
    });

    테이블 확인

    • 테이블이 잘 생성되어있는지 확인합니다. 해당 테이블 정보들이 출력됩니다.
    var params = {
        TableName: 'MusicChart',
    };
    dynamodb.describeTable(params, function(err, data) {
        if (err) {
            console.log(err); // an error occurred
        } else {
            console.log(data); // successful response
        }
    });

    테이블 목록

    • 현재 계정 및 리전에 있는 테이블의 목록을 나열합니다.
    • ExclusiveStartTableName속성과 테이블명을 포함하면 해당 테이블을 제외한 다음 순위의 테이블부터 차례대로 나열합니다.
    • Limit속성을 포함하면 반환 테이블 목록의 개수를 제한할 수 있습니다.
    var params = {
        // ExclusiveStartTableName: 'MusicChart', // optional (for pagination, returned as LastEvaluatedTableName)
        Limit: 5, // optional (to further limit the number of table names returned per page)
    };
    dynamodb.listTables(params, function(err, data) {
        if (err) {
            console.log(err); // an error occurred
        } else {
            console.log(data); // successful response
        }
    });

    테이블 삭제

    • MusicChart 테이블을 삭제합니다.
    var params = {
        TableName: 'MusicChart',
    };
    
    dynamodb.deleteTable(params, function(err, data) {
        if (err) {
            console.log(err); // error
        } else {
            console.log(data); // success
        }
    });

    항목

    항목 생성 및 업데이트

    • 새로운 항목을 생성합니다. 이 때 company(파티션 키), rank(정렬 키)와 일치하는 값이 있을 때는 기존 항목을 업데이트 합니다.
    var params = {
        TableName: "MusicChart",
        Item:{
            "company": 1,
            "rank": 1,
            "music_title": "빨간맛",
            "singer": "레드벨벳",
            "album_title": "The Red Summer - Summer Mini Album",
            "album_image": "http://www.naver.com/images/red_flavor_image.png"
        }
    };
    
    docClient.put(params, function(err, data) {
        if (err) {
            console.log(err); // error
        } else {
            console.log(data); // success
        }
    });

    여러 항목 쓰기 & 삭제 (BatchWriteItem)

    • 한번의 요청에 여러 쓰기 작업을 수행할 수 있습니다. PutRequest, DeleteRequest를 포함할 수 있습니다.
    var params = {
        RequestItems: {
            "MusicChart": [
                {
                    PutRequest: {
                        Item: { // a map of attribute name to AttributeValue    
                            "company": 1,
                            "rank": 1,
                            "music_title": "좋니",
                            "singler":"윤종신",
                            "album_title": "Yoons 1st",
                            "album_image": "http://www.naver.com/images/yoons_image.png"
                        }
                    }
                },
                {
                    DeleteRequest: {
                        Key: { 
                            "company": 1,
                            // more primary attributes (if the primary key is hash/range schema)
                        }
                    }
                },
                // ... more put or delete requests ...
            ]
        }
    };
    
    docClient.batchWrite(params, function(err, data) {
        if (err) {
            console.log(err, err.stack); // an error occurred
        } else {
            console.log(data);           // successful response
        }
    });

    항목 쿼리

    var params = {
        TableName : "MusicChart",
        KeyConditionExpression: "company = :c",
        ExpressionAttributeValues: {
            ":c":1
        }
    };
    
    docClient.query(params, function(err, data) {
        if (err) {
            console.log("Unable to query. Error:", JSON.stringify(err, null, 2));
        } else {
            console.log("Query succeeded.");
            data.Items.forEach(function(item) {
                console.log(" - " + JSON.stringify(item));
            });
        }
    });

    항목 업데이트

    var params = {
        TableName:"MusicChart",
        Key:{
            "company": 1,
            "rank": 2
        },
        UpdateExpression: "set music_title = :mt, singer=:s, album_title=:at, album_image=:ai", 
        ExpressionAttributeValues:{
            ":mt":"빨간맛",
            ":s":"레드벨벳",
            ":at":"The Red Summer - Summer Mini Album",
            ":ai":"http://www.naver.com/images/red_flavor_image.png"
        },
        ReturnValues: 'NONE', // optional (NONE | ALL_OLD | UPDATED_OLD | ALL_NEW | UPDATED_NEW)
        ReturnConsumedCapacity: 'NONE', // optional (NONE | TOTAL | INDEXES)
        ReturnItemCollectionMetrics: 'NONE', // optional (NONE | SIZE)
    };
    
    docClient.update(params, function(err, data) {
        if (err) {
            console.log(err); // error
        } else {
            console.log(data); // success
        }
    });

    항목 읽기

    • company값이 1인 항목을 불러옵니다.
    var params = {
        TableName: "MusicChart",
        Key:{
            "company": 1
        }
    };
    
    docClient.get(params, function(err, data) {
        if (err) {
            console.log(err); // error
        } else {
            console.log(data); // success
        }
    });

    항목 삭제

    • company값이 1인 항목을 삭제합니다.
    var params = {
        TableName : "MusicChart",
        KeyConditionExpression: "company = :c",
        ExpressionAttributeValues: {
            ":c":1
        }
    };
    
    docClient.delete(params, function(err, data) {
        if (err) {
            console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
        } else {
            console.log("Query succeeded.");
            data.Items.forEach(function(item) {
                console.log(" -", item.song_title + ": " + item.album_title);
            });
        }
    });


    [참고자료]
    JavaScript SDK Doc
    http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#batchWriteItem-property

    AWS Doc
    http://docs.aws.amazon.com/ko_kr/amazondynamodb/latest/developerguide/GettingStarted.NodeJs.03.html#GettingStarted.NodeJs.03.03

    facebook twitter googleplus kakaostory naver