• 沒有找到結果。

(Optional): Delete the Table

在文檔中 Amazon DynamoDB (頁 113-148)

Step 5: (Optional) Delete the Table

To delete the Movies table:

1. Copy the following program and paste it into your Java development environment.

/**

* 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.

*/

package com.amazonaws.codesamples.gsg;

import com.amazonaws.client.builder.AwsClientBuilder;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;

import com.amazonaws.services.dynamodbv2.document.DynamoDB;

import com.amazonaws.services.dynamodbv2.document.Table;

public class MoviesDeleteTable {

public static void main(String[] args) throws Exception {

AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() .withEndpointConfiguration(new

AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) .build();

DynamoDB dynamoDB = new DynamoDB(client);

Table table = dynamoDB.getTable("Movies");

try {

System.out.println("Attempting to delete table; please wait...");

table.delete();

table.waitForDelete();

System.out.print("Success.");

}

catch (Exception e) {

System.err.println("Unable to delete table: ");

System.err.println(e.getMessage());

} } }

2. Compile and run the program.

Summary

Summary

In this tutorial, you created the Movies table in Amazon DynamoDB on your computer and performed basic operations. The downloadable version of DynamoDB is useful during application development and testing. However, when you're ready to run your application in a production environment, you must modify your code so that it uses the DynamoDB web service.

Modifying the Code to Use the DynamoDB Service

To use the DynamoDB service, you must change the endpoint in your application.

1. Remove the following import.

import com.amazonaws.client.builder.AwsClientBuilder;

2. Next, go to AmazonDynamoDB in the code.

AmazonDynamoDB client =

AmazonDynamoDBClientBuilder.standard().withEndpointConfiguration(

new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) .build();

3. Now modify the client so that it accesses an AWS Region instead of a specific endpoint.

AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() .withRegion(Regions.REGION)

.build();

For example, if you want to access the us-west-2 region, you would do the following.

AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() .withRegion(Regions.US_WEST_2)

.build();

Instead of using DynamoDB on your computer, the program now uses the DynamoDB web service endpoint in the US West (Oregon) Region.

DynamoDB is available in AWS Regions worldwide. For the complete list, see Regions and Endpoints in the AWS General Reference. For more information about setting Regions and endpoints in your code, see AWS Region Selection in the AWS SDK for Java Developer Guide.

Getting Started with JavaScript and DynamoDB

In this tutorial, you use JavaScript to write simple programs to perform the following Amazon DynamoDB operations:

• Create a table called Movies and load sample data in JSON format.

• Perform create, read, update, and delete operations on the table.

• Run simple queries.

As you work through this tutorial, you can refer to the AWS SDK for JavaScript API Reference.

Tutorial Prerequisites

Tutorial Prerequisites

• Download and run DynamoDB on your computer. For more information, see Setting Up DynamoDB Local (Downloadable Version) (p. 50).

NoteYou use the downloadable version of DynamoDB in this tutorial. For information about how to run the same code against the DynamoDB web service, see the Summary and Review of JavaScript and DynamoDB Tutorial (p. 125).

• Set up an AWS access key to use AWS SDKs. For more information, see Setting Up DynamoDB (Web Service) (p. 57).

• Set up the AWS SDK for JavaScript. To do this, add or modify the following script tag to your HTML pages:

<script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script>

NoteThe version of AWS SDK for JavaScript might have been updated. For the latest version, see the AWS SDK for JavaScript API Reference.

• Enable cross-origin resource sharing (CORS) so that your computer's browser can communicate with the downloadable version of DynamoDB.

To enable CORS

1. Download the free ModHeader Chrome browser extension (or any other browser extension that allows you to modify HTTP response headers).

2. Run the ModHeader Chrome browser extension, and add an HTTP response header with the name set to "Access-Control-Allow-Origin" and a value of "null" or "*".

Important

This configuration is required only while running this tutorial program for JavaScript on your computer. After you finish the tutorial, you should disable or remove this configuration.

3. You can now run the JavaScript tutorial program files.

If you prefer to run a complete version of the JavaScript tutorial program instead of performing step-by-step instructions, do the following:

1. Download the following file: MoviesJavaScript.zip.

2. Extract the file MoviesJavaScript.html from the archive.

3. Modify the MoviesJavaScript.html file to use your endpoint.

4. Run the MoviesJavaScript.html file.

Step 1: Create a DynamoDB Table with JavaScript

In this step, you create a table named Movies. The primary key for the table is composed of the following attributes:

• year – The partition key. The AttributeType is N for number.

• title – The sort key. The AttributeType is S for string.

1. Copy the following program and paste it into a file named MoviesCreateTable.html.

Step 1: Create a Table

<!--

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.

-->

// 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 dynamodb = new AWS.DynamoDB();

function createMovies() {

dynamodb.createTable(params, function(err, data) { if (err) {

document.getElementById('textarea').innerHTML = "Unable to create table: "

+ "\n" + JSON.stringify(err, undefined, 2);

} else {

document.getElementById('textarea').innerHTML = "Created table: " + "\n" + JSON.stringify(data, undefined, 2);

Step 2: Load Sample Data

<body>

<input id="createTableButton" type="button" value="Create Table"

onclick="createMovies();" />

<br><br>

<textarea readonly id= "textarea" style="width:400px; height:800px"></textarea>

</body>

</html>

Note

• You set the endpoint to indicate that you are creating the table in Amazon DynamoDB on your computer.

• In the createMovies function, you specify the table name, primary key attributes, and its data types.

• The ProvisionedThroughput parameter is required, but the downloadable version of DynamoDB ignores it. (Provisioned throughput is beyond the scope of this tutorial.) 2. Open the MoviesCreateTable.html file in your browser.

3. Choose Create Table.

To learn more about managing tables, see Working with Tables and Data in DynamoDB (p. 338).

Step 2: Load Sample Data with JavaScript into DynamoDB

In this step, you populate the Movies table with sample data.

Topics

• Step 2.1: Download the Sample Data File (p. 107)

• Step 2.2: Load the Sample Data into the Movies Table (p. 107)

This scenario uses a sample data file that contains information about a few thousand movies from the Internet Movie Database (IMDb). The movie data is in JSON format, as shown in the following example.

For each movie, there is a year, a title, and a JSON map named info.

[ {

"year" : ... , "title" : ... , "info" : { ... } },

{

"year" : ..., "title" : ..., "info" : { ... } },

...

]

In the JSON data, note the following:

• The year and title are used as the primary key attribute values for the Movies table.

Step 2: Load Sample Data

• The rest of the info values are stored in a single attribute called info. This program illustrates how you can store JSON in an Amazon DynamoDB attribute.

The following is an example of movie data.

{ "year" : 2013,

"title" : "Turn It Down, Or Else!", "info" : {

"directors" : [ "Alice Smith", "Bob Jones"

],

"release_date" : "2013-01-18T00:00:00Z", "rating" : 6.2,

"genres" : [ "Comedy", "Drama"

],

"image_url" : "http://ia.media-imdb.com/images/N/

O9ERWAU7FS797AJ7LU8HN09AMUP908RLlo5JF90EWR7LJKQ7@@._V1_SX400_.jpg",

"plot" : "A rock band plays their music at high volumes, annoying the neighbors.", "rank" : 11,

"running_time_secs" : 5215, "actors" : [

"David Matthewman", "Ann Thomas", "Jonathan G. Neff"

] } }

Step 2.1: Download the Sample Data File

1. Download the sample data archive: moviedata.zip 2. Extract the data file (moviedata.json) from the archive.

3. Copy and paste the moviedata.json file into your current directory.

Step 2.2: Load the Sample Data into the Movies Table

After you download the sample data, you can run the following program to populate the Movies table.

1. Copy the following program and paste it into a file named MoviesLoadData.html.

<!--

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.

-->

<html>

Step 2: Load Sample Data

// 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 processFile(evt) {

document.getElementById('textarea').innerHTML = "";

document.getElementById('textarea').innerHTML += "Importing movies into DynamoDB.

Please wait..." + "\n";

var file = evt.target.files[0]; movie: " + count + movie.title + "\n";

document.getElementById('textarea').innerHTML += "Error JSON: "

+ JSON.stringify(err) + "\n";

} else {

document.getElementById('textarea').innerHTML += "PutItem succeeded: " + movie.title + "\n";

textarea.scrollTop = textarea.scrollHeight;

Step 3: Create, Read, Update, and Delete an Item

<input type="file" id="fileinput" accept='application/json'/>

<br><br>

<textarea readonly id= "textarea" style="width:400px; height:800px"></textarea>

<script>

document.getElementById('fileinput').addEventListener('change', processFile, false);

</script>

</body>

</html>

2. Open the MoviesLoadData.html file in your browser.

3. Choose Browse, and load the moviedata.json file.

Step 3: Create, Read, Update, and Delete an Item

In this step, you perform read and write operations on an item in the Movies table.

To learn more about reading and writing data, see Working with Items and Attributes (p. 402).

Topics

• Step 3.1: Create a New Item (p. 109)

• Step 3.2: Read an Item (p. 110)

• Step 3.3: Update an Item (p. 112)

• Step 3.4: Increment an Atomic Counter (p. 114)

• Step 3.5: Update an Item (Conditionally) (p. 115)

• Step 3.6: Delete an Item (p. 117)

Step 3.1: Create a New Item

In this step, you add a new item to the Movies table.

1. Copy the following program and paste it into a file named MoviesItemOps01.html.

<!--

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.

-->

<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.

Step 3: Create, Read, Update, and Delete an Item

// 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() {

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);

}

<input id="createItem" type="button" value="Create Item" onclick="createItem();" />

<br><br>

<textarea readonly id= "textarea" style="width:400px; height:800px"></textarea>

</body>

</html>

Note

The primary key is required. This code adds an item that has a primary key (year, title) and info attributes. The info attribute stores sample JSON that provides more information about the movie.

2. Open the MoviesItemOps01.html file in your browser.

3. Choose Create Item.

Step 3.2: Read an Item

In the previous program, you added the following item to the table.

{ year: 2015,

title: "The Big New Movie", info: {

Step 3: Create, Read, Update, and Delete an Item

plot: "Nothing happens at all.", rating: 0

}}

You can use the get method to read the item from the Movies table. You must specify the primary key values, so you can read any item from Movies if you know its year and title.

1. Copy the following program and paste it into a file named MoviesItemOps02.html.

<!--

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.

-->

// 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() {

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);

}

Step 3: Create, Read, Update, and Delete an Item

});

}

</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. Open the MoviesItemOps02.html file in your browser.

3. Choose Read Item.

Step 3.3: Update an Item

You can use the update method to modify an item. You can update values of existing attributes, add new attributes, or remove attributes.

In this example, you perform the following updates:

• Change the value of the existing attributes (rating, plot).

• Add a new list attribute (actors) to the existing info map.

The item changes from the following:

{ year: 2015,

title: "The Big New Movie", info: {

plot: "Nothing happens at all.", rating: 0

}}

To this:

{ year: 2015,

title: "The Big New Movie", info: {

plot: "Everything happens all at once.", rating: 5.5,

actors: ["Larry", "Moe", "Curly"]

}}

1. Copy the following program and paste it into a file named MoviesItemOps03.html.

<!--

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

Step 3: Create, Read, Update, and Delete an Item

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.

-->

// 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() {

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);

}

<input id="updateItem" type="button" value="Update Item" onclick="updateItem();" />

<br><br>

<textarea readonly id= "textarea" style="width:400px; height:800px"></textarea>

Step 3: Create, Read, Update, and Delete an Item

</body>

</html>

NoteThis program uses UpdateExpression to describe all updates you want to perform on the specified item.

The ReturnValues parameter instructs Amazon DynamoDB to return only the updated attributes ("UPDATED_NEW").

2. Open the MoviesItemOps03.html file in your browser.

3. Choose Update Item.

Step 3.4: Increment an Atomic Counter

DynamoDB supports atomic counters, where you use the update method to increment or decrement the value of an attribute without interfering with other write requests. (All write requests are applied in the order in which they are received.)

The following program shows how to increment the rating for a movie. Each time you run it, the program increments this attribute by one.

1. Copy the following program and paste it into a file named MoviesItemOps04.html.

<!--

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.

-->

<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";

Step 3: Create, Read, Update, and Delete an Item

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. Open the MoviesItemOps04.html file in your browser.

2. Open the MoviesItemOps04.html file in your browser.

在文檔中 Amazon DynamoDB (頁 113-148)

相關文件