Amazon DynamoDB
入门指南 (API Version 2012-08-10)
AWS 服务或AWS文档中描述的功能,可能因地区/位置而异。点 击 Getting Started with Amazon AWS to see specific differences applicable to the China (Beijing) Region.

步骤 3:创建、读取、更新和删除项目

在此步骤中,您将对 Movies 表中的项目执行读写操作。

要了解有关数据读写的更多信息,请参阅 Amazon DynamoDB 开发人员指南 中的处理项目

步骤 3.1:创建新项目

在此步骤中,您将向 Movies 表中添加一个新项目。

  1. 将以下程序复制到名为 MoviesItemOps01.html 的文件中:

    Copy
    <html> <head> <script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script> <script> AWS.config.update({ region: "us-west-2", endpoint: 'http://localhost:8000', // accessKeyId default can be used while using the downloadable version of DynamoDB. // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead. accessKeyId: "fakeMyKeyId", // secretAccessKey default can be used while using the downloadable version of DynamoDB. // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead. secretAccessKey: "fakeSecretAccessKey" }); var docClient = new AWS.DynamoDB.DocumentClient(); function createItem() { var params = { TableName :"Movies", Item:{ "year": 2015, "title": "The Big New Movie", "info":{ "plot": "Nothing happens at all.", "rating": 0 } } }; docClient.put(params, function(err, data) { if (err) { document.getElementById('textarea').innerHTML = "Unable to add item: " + "\n" + JSON.stringify(err, undefined, 2); } else { document.getElementById('textarea').innerHTML = "PutItem succeeded: " + "\n" + JSON.stringify(data, undefined, 2); } }); } </script> </head> <body> <input id="createItem" type="button" value="Create Item" onclick="createItem();" /> <br><br> <textarea readonly id= "textarea" style="width:400px; height:800px"></textarea> </body> </html>

    注意

    主键是必填项。此代码将添加一个具有主键 (yeartitle) 和 info 属性的项目。info 属性用于存储示例 JSON,其中提供有关电影的更多信息。

  2. 在您的浏览器上打开 MoviesItemOps01.html 文件。

  3. 选择 Create Item

步骤 3.2:读取项目

在上一个程序中,您已向表中添加了以下项目:

Copy
{ year: 2015, title: "The Big New Movie", info: { plot: "Nothing happens at all.", rating: 0 } }

您可以使用 get 方法读取 Movies 表中的项目。您必须指定主键值,以便在知道 Movies 中的任何项目的 yeartitle 的情况下读取该项目。

  1. 将以下程序复制到名为 MoviesItemOps02.html 的文件中:

    Copy
    <html> <head> <script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script> <script> AWS.config.update({ region: "us-west-2", endpoint: 'http://localhost:8000', // accessKeyId default can be used while using the downloadable version of DynamoDB. // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead. accessKeyId: "fakeMyKeyId", // secretAccessKey default can be used while using the downloadable version of DynamoDB. // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead. secretAccessKey: "fakeSecretAccessKey" }); var docClient = new AWS.DynamoDB.DocumentClient(); function readItem() { 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) { document.getElementById('textarea').innerHTML = "Unable to read item: " + "\n" + JSON.stringify(err, undefined, 2); } else { document.getElementById('textarea').innerHTML = "GetItem succeeded: " + "\n" + JSON.stringify(data, undefined, 2); } }); } </script> </head> <body> <input id="readItem" type="button" value="Read Item" onclick="readItem();" /> <br><br> <textarea readonly id= "textarea" style="width:400px; height:800px"></textarea> </body> </html>
  2. 在您的浏览器上打开 MoviesItemOps02.html 文件。

  3. 选择 Read Item

步骤 3.3:更新项目

您可以使用 update 方法修改项目。您可以更新现有属性的值、添加新属性或删除属性。

在此示例中,您可以执行以下更新:

  • 更改现有属性 (ratingplot) 的值。

  • 向现有 info 映射中添加新的列表属性 (actors)。

项目将在以下基础上进行更改:

Copy
{ year: 2015, title: "The Big New Movie", info: { plot: "Nothing happens at all.", rating: 0 } }

更改为以下项目:

Copy
{ year: 2015, title: "The Big New Movie", info: { plot: "Everything happens all at once.", rating: 5.5, actors: ["Larry", "Moe", "Curly"] } }
  1. 将以下程序复制到名为 MoviesItemOps03.html 的文件中:

    Copy
    <html> <head> <script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script> <script> AWS.config.update({ region: "us-west-2", endpoint: 'http://localhost:8000', // accessKeyId default can be used while using the downloadable version of DynamoDB. // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead. accessKeyId: "fakeMyKeyId", // secretAccessKey default can be used while using the downloadable version of DynamoDB. // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead. secretAccessKey: "fakeSecretAccessKey" }); var docClient = new AWS.DynamoDB.DocumentClient(); function updateItem() { var table = "Movies"; var year = 2015; var title = "The Big New Movie"; 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" }; docClient.update(params, function(err, data) { if (err) { document.getElementById('textarea').innerHTML = "Unable to update item: " + "\n" + JSON.stringify(err, undefined, 2); } else { document.getElementById('textarea').innerHTML = "UpdateItem succeeded: " + "\n" + JSON.stringify(data, undefined, 2); } }); } </script> </head> <body> <input id="updateItem" type="button" value="Update Item" onclick="updateItem();" /> <br><br> <textarea readonly id= "textarea" style="width:400px; height:800px"></textarea> </body> </html>

    注意

    此程序使用 UpdateExpression 来描述您要对指定项目执行的所有更新。

    ReturnValues 参数用于指示 DynamoDB 仅返回更新后的属性 ("UPDATED_NEW")。

  2. 在您的浏览器上打开 MoviesItemOps03.html 文件。

  3. 选择 Update Item

步骤 3.4:递增一个原子计数器

DynamoDB 支持原子计数器,以便您使用 update 方法来递增或递减属性的值,而不干扰其他写入请求。 (所有写入请求的应用顺序跟接收顺序相同。)

以下程序演示了如何递增电影的 rating。每次运行此程序时,此属性都会递增 1。

  1. 将以下程序复制到名为 MoviesItemOps04.html 的文件中:

    Copy
    <html> <head> <script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script> <script> AWS.config.update({ region: "us-west-2", endpoint: 'http://localhost:8000', // accessKeyId default can be used while using the downloadable version of DynamoDB. // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead. accessKeyId: "fakeMyKeyId", // secretAccessKey default can be used while using the downloadable version of DynamoDB. // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead. secretAccessKey: "fakeSecretAccessKey" }); var docClient = new AWS.DynamoDB.DocumentClient(); function increaseRating() { var table = "Movies"; var year = 2015; var title = "The Big New Movie"; var params = { TableName:table, Key:{ "year": year, "title": title }, UpdateExpression: "set info.rating = info.rating + :val", ExpressionAttributeValues:{ ":val":1 }, ReturnValues:"UPDATED_NEW" }; docClient.update(params, function(err, data) { if (err) { document.getElementById('textarea').innerHTML = "Unable to update rating: " + "\n" + JSON.stringify(err, undefined, 2); } else { document.getElementById('textarea').innerHTML = "Increase Rating succeeded: " + "\n" + JSON.stringify(data, undefined, 2); } }); } </script> </head> <body> <input id="increaseRating" type="button" value="Increase Rating" onclick="increaseRating();" /> <br><br> <textarea readonly id= "textarea" style="width:400px; height:800px"></textarea> </body> </html>
  2. 在您的浏览器上打开 MoviesItemOps04.html 文件。

  3. 选择 Increase Rating

步骤 3.5:更新项目 (有条件)

以下程序演示了如何使用有条件的 UpdateItem。如果条件为真,则更新成功;否则,不执行更新。

在此示例中,仅当有超过 3 位男演员时,才会更新项目。

  1. 将以下程序复制到名为 MoviesItemOps05.html 的文件中:

    Copy
    <html> <head> <script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script> <script> AWS.config.update({ region: "us-west-2", endpoint: 'http://localhost:8000', // accessKeyId default can be used while using the downloadable version of DynamoDB. // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead. accessKeyId: "fakeMyKeyId", // secretAccessKey default can be used while using the downloadable version of DynamoDB. // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead. secretAccessKey: "fakeSecretAccessKey" }); var docClient = new AWS.DynamoDB.DocumentClient(); function conditionalUpdate() { 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" }; docClient.update(params, function(err, data) { if (err) { document.getElementById('textarea').innerHTML = "The conditional update failed: " + "\n" + JSON.stringify(err, undefined, 2); } else { document.getElementById('textarea').innerHTML = "The conditional update succeeded: " + "\n" + JSON.stringify(data, undefined, 2); } }); } </script> </head> <body> <input id="conditionalUpdate" type="button" value="Conditional Update" onclick="conditionalUpdate();" /> <br><br> <textarea readonly id= "textarea" style="width:400px; height:800px"></textarea> </body> </html>
  2. 在您的浏览器上打开 MoviesItemOps05.html 文件。

  3. 选择 Conditional Update

    程序应该会失败并显示以下消息:

    The conditional update failed

    这是因为电影包含三位男演员,但此条件是检查男演员数量是否大于 3。

  4. 修改程序,以使 ConditionExpression 如下所示:

    Copy
    ConditionExpression: "size(info.actors) >= :num",

    此时,条件变成大于或等于 3,而不是大于 3

  5. 重新运行程序。updateItem 操作这次应该会成功。

步骤 3.6:删除项目

您可以使用 delete 方法,通过指定项目的主键来删除一个项目。您可以提供一个 ConditionExpression,避免在不符合条件时删除项目。

在以下示例中,您将尝试删除评分为 5 分或更低的特定电影项目。

  1. 将以下程序复制到名为 MoviesItemOps06.html 的文件中:

    Copy
    <html> <head> <script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script> <script> AWS.config.update({ region: "us-west-2", endpoint: 'http://localhost:8000', // accessKeyId default can be used while using the downloadable version of DynamoDB. // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead. accessKeyId: "fakeMyKeyId", // secretAccessKey default can be used while using the downloadable version of DynamoDB. // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead. secretAccessKey: "fakeSecretAccessKey" }); var docClient = new AWS.DynamoDB.DocumentClient(); function conditionalDelete() { 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 } }; docClient.delete(params, function(err, data) { if (err) { document.getElementById('textarea').innerHTML = "The conditional delete failed: " + "\n" + JSON.stringify(err, undefined, 2); } else { document.getElementById('textarea').innerHTML = "The conditional delete succeeded: " + "\n" + JSON.stringify(data, undefined, 2); } }); } </script> </head> <body> <input id="conditionalDelete" type="button" value="Conditional Delete" onclick="conditionalDelete();" /> <br><br> <textarea readonly id= "textarea" style="width:400px; height:800px"></textarea> </body> </html>
  2. 在您的浏览器上打开 MoviesItemOps06.html 文件。

  3. 选择 Conditional Delete

    程序应该会失败并显示以下消息:

    The conditional delete failed

    这是因为此特定电影的评分高于 5 分。

  4. 修改程序,以便从 params 中移除条件。

    Copy
    var params = { TableName:table, Key:{ "title":title, "year":year } };
  5. 重新运行程序。因为您已移除条件,所以删除操作将会成功。