기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
단계 3: 항목 생성, 읽기, 업데이트 및 삭제
이 단계에서는 Movies
테이블의 한 항목에 대해 읽기 및 쓰기 작업을 수행합니다.
데이터 읽기 및 쓰기에 대한 자세한 내용은 항목 및 속성 작업 단원을 참조하십시오.
주제
단계 3.1: 새 항목 생성
이 단계에서는 Movies
테이블에 새 항목을 추가합니다.
-
다음 프로그램을 복사한 후 이름이
MoviesItemOps01.js
인 파일에 붙여 넣습니다./** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", endpoint: "http://localhost:8000" }); var docClient = new AWS.DynamoDB.DocumentClient(); var table = "Movies"; var year = 2015; var title = "The Big New Movie"; var params = { TableName:table, Item:{ "year": year, "title": title, "info":{ "plot": "Nothing happens at all.", "rating": 0 } } }; console.log("Adding a new item..."); docClient.put(params, function(err, data) { if (err) { console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2)); } else { console.log("Added item:", JSON.stringify(data, null, 2)); } });
참고 기본 키가 필요합니다. 이 코드는 기본 키(
year
,title
) 및info
속성을 지닌 항목을 추가합니다.info
속성은 영화에 대한 자세한 정보를 제공하는 샘플 JSON을 저장합니다. -
프로그램을 실행하려면 다음 명령을 입력합니다.
node MoviesItemOps01.js
단계 3.2: 항목 읽기
이전 프로그램에서 테이블에 다음 항목을 추가했습니다.
{ year: 2015, title: "The Big New Movie", info: { plot: "Nothing happens at all.", rating: 0 } }
get
메서드를 사용하여 Movies
테이블에서 항목을 읽어올 수 있습니다. 기본 키 값을 지정해야 Movies
과 year
을 알고 있을 때 title
에서 항목을 읽어올 수 있습니다.
-
다음 프로그램을 복사한 후 이름이
MoviesItemOps02.js
인 파일에 붙여 넣습니다./** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", endpoint: "http://localhost:8000" }); var docClient = new AWS.DynamoDB.DocumentClient(); var table = "Movies"; var year = 2015; var title = "The Big New Movie"; var params = { TableName: table, Key:{ "year": year, "title": title } }; docClient.get(params, function(err, data) { if (err) { console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2)); } else { console.log("GetItem succeeded:", JSON.stringify(data, null, 2)); } });
-
프로그램을 실행하려면 다음 명령을 입력합니다.
node MoviesItemOps02.js
3.3단계: 항목 업데이트
update
메서드를 사용해 기존 항목을 수정할 수 있습니다. 기존 속성의 값을 업데이트하거나 새로운 속성을 추가하거나 속성을 제거할 수 있습니다.
이 예시에서는 다음과 같이 업데이트를 수행합니다.
-
기존 속성(
rating
,plot
)의 값을 변경합니다. -
기존
info
맵에 새로운 목록 속성(actors
)을 추가합니다.
이전에 테이블에 다음 항목을 추가했습니다.
{ year: 2015, title: "The Big New Movie", info: { plot: "Nothing happens at all.", rating: 0 } }
항목은 다음과 같이 업데이트됩니다.
{ year: 2015, title: "The Big New Movie", info: { plot: "Everything happens all at once.", rating: 5.5, actors: ["Larry", "Moe", "Curly"] } }
-
다음 프로그램을 복사한 후 이름이
MoviesItemOps03.js
인 파일에 붙여 넣습니다./** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", endpoint: "http://localhost:8000" }); var docClient = new AWS.DynamoDB.DocumentClient() var table = "Movies"; var year = 2015; var title = "The Big New Movie"; // Update the item, unconditionally, var params = { TableName:table, Key:{ "year": year, "title": title }, UpdateExpression: "set info.rating = :r, info.plot=:p, info.actors=:a", ExpressionAttributeValues:{ ":r":5.5, ":p":"Everything happens all at once.", ":a":["Larry", "Moe", "Curly"] }, ReturnValues:"UPDATED_NEW" }; console.log("Updating the item..."); docClient.update(params, function(err, data) { if (err) { console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2)); } else { console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2)); } });
참고 이 프로그램은 지정된 항목에 대해 수행하고자 하는 모든 업데이트를 설명하기 위해
UpdateExpression
을 사용합니다.ReturnValues
파라미터는 DynamoDB에게 업데이트된 속성("UPDATED_NEW"
)만 반환하도록 지시합니다. -
프로그램을 실행하려면 다음 명령을 입력합니다.
node MoviesItemOps03.js
단계 3.4: 원자성 카운터 증가시키기
DynamoDB는 원자성 카운터를 지원합니다. 원자성 카운터에서는 update
메서드를 사용하여 다른 쓰기 요청을 방해하지 않으면서 기존 속성의 값을 증가시키거나 감소시킬 수 있습니다. (모든 쓰기 요청은 수신된 순서대로 적용됩니다.)
다음 프로그램은 영화에 대한 rating
을 증가시키는 방법을 보여줍니다. 이 프로그램을 실행할 때마다 이 속성이 1씩 증가합니다.
-
다음 프로그램을 복사한 후 이름이
MoviesItemOps04.js
인 파일에 붙여 넣습니다./** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", endpoint: "http://localhost:8000" }); var docClient = new AWS.DynamoDB.DocumentClient() var table = "Movies"; var year = 2015; var title = "The Big New Movie"; // Increment an atomic counter var params = { TableName:table, Key:{ "year": year, "title": title }, UpdateExpression: "set info.rating = info.rating + :val", ExpressionAttributeValues:{ ":val": 1 }, ReturnValues:"UPDATED_NEW" }; console.log("Updating the item..."); docClient.update(params, function(err, data) { if (err) { console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2)); } else { console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2)); } });
-
프로그램을 실행하려면 다음 명령을 입력합니다.
node MoviesItemOps04.js
단계 3.5: 항목 업데이트(조건부)
다음 프로그램은 UpdateItem
을 조건과 함께 사용하는 방법을 보여줍니다. 조건이 true로 평가되면 업데이트가 성공하지만, 그렇지 않으면 업데이트가 수행되지 않습니다.
이 경우에는 영화에서 배우가 3명보다 많은 경우에만 항목이 업데이트됩니다.
-
다음 프로그램을 복사한 후 이름이
MoviesItemOps05.js
인 파일에 붙여 넣습니다./** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", endpoint: "http://localhost:8000" }); var docClient = new AWS.DynamoDB.DocumentClient() var table = "Movies"; var year = 2015; var title = "The Big New Movie"; // Conditional update (will fail) var params = { TableName:table, Key:{ "year": year, "title": title }, UpdateExpression: "remove info.actors[0]", ConditionExpression: "size(info.actors) > :num", ExpressionAttributeValues:{ ":num": 3 }, ReturnValues:"UPDATED_NEW" }; console.log("Attempting a conditional update..."); docClient.update(params, function(err, data) { if (err) { console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2)); } else { console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2)); } });
-
프로그램을 실행하려면 다음 명령을 입력합니다.
node MoviesItemOps05.js
프로그램이 실패하고 다음 메시지가 표시됩니다.
The conditional request failed
이렇게 되는 이유는 영화에는 3명의 배우가 있는데, 배우가 3명보다 많은지를 조건이 확인하고 있기 때문입니다.
-
ConditionExpression
이 다음과 같이 되도록 프로그램을 수정합니다.ConditionExpression: "size(info.actors) >= :num",
조건은 이제 3보다 큼 대신 3보다 크거나 같음이 되었습니다.
-
프로그램을 다시 실행합니다.
updateItem
작업은 이제 성공합니다.
단계 3.6: 항목 삭제
delete
메서드를 사용해 기본 키를 지정함으로써 항목 1개를 삭제할 수 있습니다. 조건을 만족하지 않는 경우 ConditionExpression
을 제공해 항목 삭제를 방지하는 옵션을 선택할 수 있습니다.
다음 예제에서는 평점이 5 이하인 경우 특정 영화 항목을 삭제하고자 합니다.
-
다음 프로그램을 복사한 후 이름이
MoviesItemOps06.js
인 파일에 붙여 넣습니다./** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", endpoint: "http://localhost:8000" }); var docClient = new AWS.DynamoDB.DocumentClient(); var table = "Movies"; var year = 2015; var title = "The Big New Movie"; var params = { TableName:table, Key:{ "year": year, "title": title }, ConditionExpression:"info.rating <= :val", ExpressionAttributeValues: { ":val": 5.0 } }; console.log("Attempting a conditional delete..."); docClient.delete(params, function(err, data) { if (err) { console.error("Unable to delete item. Error JSON:", JSON.stringify(err, null, 2)); } else { console.log("DeleteItem succeeded:", JSON.stringify(data, null, 2)); } });
-
프로그램을 실행하려면 다음 명령을 입력합니다.
node MoviesItemOps06.js
프로그램이 실패하고 다음 메시지가 표시됩니다.
The conditional request failed
이는 이 특정 영화에 대한 평점이 5보다 크기 때문입니다.
-
프로그램을 수정해
params
에서 조건을 제거합니다.var params = { TableName:table, Key:{ "title":title, "year":year } };
-
프로그램을 다시 실행합니다. 조건을 제거했으므로 이제 삭제는 성공합니다.