02.amazon dynamodb

Upload: hector

Post on 22-Feb-2018

229 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/24/2019 02.Amazon DynamoDB

    1/70

  • 7/24/2019 02.Amazon DynamoDB

    2/70

    Amazon DynamoDB: Getting Started GuideCopyright 2015 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.

    The following are trademarks of Amazon Web Services, Inc.: Amazon, Amazon Web Services Design, AWS, Amazon CloudFront,AWS CloudTrail, AWS CodeDeploy, Amazon Cognito, Amazon DevPay, DynamoDB, ElastiCache, Amazon EC2, Amazon ElasticCompute Cloud, Amazon Glacier, Amazon Kinesis, Kindle, Kindle Fire, AWS Marketplace Design, Mechanical Turk, Amazon Redshift,

    Amazon Route 53, Amazon S3, Amazon VPC, and Amazon WorkDocs. In addition, Amazon.com graphics, logos, page headers,button icons, scripts, and service names are trademarks, or trade dress of Amazon in the U.S. and/or other countries. Amazon'strademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that islikely to cause confusion among customers, or in any manner that disparages or discredits Amazon.

    All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connectedto, or sponsored by Amazon.

    Amazon DynamoDB Getting Started Guide

  • 7/24/2019 02.Amazon DynamoDB

    3/70

    Table of Contents

    Getting Started with Amazon DynamoDB .......................................................................................... 1Introduction to DynamoDB Concepts ........................................................................................ 1

    Tables ......................................................................................................................... 1Items ........................................................................................................................... 2Attributes ..................................................................................................................... 2Primary Key ................................................................................................................. 2Secondary Indexes ........................................................................................................ 2

    Next Step ............................................................................................................................. 2Tutorial: Basic DynamoDB Operations ............................................................................................... 3

    Prerequisites ........................................................................................................................ 4Download and Run DynamoDB ........................................................................................ 4Next Step ..................................................................................................................... 4

    Step 1: Create a Table ............................................................................................................ 5Next Step ..................................................................................................................... 6

    Step 2: Get Information About Tables ........................................................................................ 6Step 2.1: Retrieve a Table Description ............................................................................... 6Step 2.2: Retrieve a List of Your Tables .............................................................................. 7

    Next Step ..................................................................................................................... 7Step 3: Write Items to the Table ................................................................................................ 7Step 3.1: Write a Single Item ........................................................................................... 8Step 3.3: Write Multiple Items .......................................................................................... 9Next Step ................................................................................................................... 11

    Step 4: Read an Item Using Its Primary Key ............................................................................. 11Step 4.1: Read an Item Using GetItem ............................................................................. 11Step 4.2: Retrieve a Subset of Attributes Using a Projection Expression ................................ 12Step 4.4: Read Multiple Items Using BatchGetItem ............................................................ 14Next Step ................................................................................................................... 15

    Step 5: Query and Scan the Table ........................................................................................... 15Step 5.1: Run a Query .................................................................................................. 16Step 5.2: Filter Query Results ........................................................................................ 17Step 5.3: Scan the Table ............................................................................................... 17

    Next Step ................................................................................................................... 18Step 6: Work with a Secondary Index ...................................................................................... 18

    Step 6.1: Create a Global Secondary Index ...................................................................... 18Step 6.2: Query the Index .............................................................................................. 20Step 6.3: Scan the Index ............................................................................................... 20Next Step ................................................................................................................... 21

    Step 7: Modify Items in the Table ............................................................................................ 21Step 7.1: Update an Item .............................................................................................. 21Step 7.2: Delete an Item ............................................................................................... 24Next Step ................................................................................................................... 25

    Step 8: Clean Up ................................................................................................................. 25Next Step ................................................................................................................... 26

    Summary ........................................................................................................................... 26Next Steps ................................................................................................................. 26

    Tutorial: Node.js and DynamoDB .................................................................................................... 27Prerequisites ...................................................................................................................... 27Step 1: Create a Table .......................................................................................................... 28Step 2: Load Sample Data ..................................................................................................... 29

    Step 2.1: Download the Sample Data File ........................................................................ 30Step 2.2: Load the Sample Data Into the Movies Table ....................................................... 30

    Step 3: Put, Update, and Delete an Item .................................................................................. 31Step 3.1: Add a New Item (PutItem) ................................................................................ 31Step 3.2: Add an Item, Specify Condition (PutItem) ............................................................ 32Step 3.3: Update the Item (UpdateItem) ........................................................................... 34

    API Version 2012-08-10

    iii

    Amazon DynamoDB Getting Started Guide

  • 7/24/2019 02.Amazon DynamoDB

    4/70

    Step 3.4: Increment an Atomic Counter (UpdateItem) ......................................................... 36Step 3.5: Update Item with a Condition (UpdateItem) ......................................................... 37Step 3.6: Delete an Item (DeleteItem) .............................................................................. 38

    Step 4: Query and Scan the Data ........................................................................................... 40Query - All Movies Released in a Year ............................................................................. 40Query - All Movies Released in a Year with Certain Titles .................................................... 41

    Step 4.2: Scan ............................................................................................................ 42Step 5: (Optional): Delete the Table ......................................................................................... 44Summary ........................................................................................................................... 44

    Using the Amazon DynamoDB Service ............................................................................ 44Tutorial: Java and DynamoDB ........................................................................................................ 47

    Prerequisites ...................................................................................................................... 47Step 1: Create a Table .......................................................................................................... 48Step 2: Load Sample Data ..................................................................................................... 49

    Step 2.1: Download the Sample Data .............................................................................. 50Step 2.2: Load the Sample Data Into the Movies Table ....................................................... 50

    Step 3: Put, Update, and Delete an Item .................................................................................. 52Step 3.1: Add a New Item (PutItem) ................................................................................ 52Step 3.2: Add an Item, Specify Condition (PutItem) ............................................................ 53Step 3.3: Update the Item (UpdateItem) ........................................................................... 55

    Step 3.4: Increment an Atomic Counter (UpdateItem) ......................................................... 56Step 3.5: Update Item with a Condition (UpdateItem) ......................................................... 57Step 3.6: Delete an Item (DeleteItem) .............................................................................. 58

    Step 4: Query and Scan the Data ........................................................................................... 60Step 4.1: Query ........................................................................................................... 60Step 4.2: Scan ............................................................................................................ 62

    Step 5: (Optional) Delete the Table .......................................................................................... 63Summary ........................................................................................................................... 64

    Using the Amazon DynamoDB Service ............................................................................ 64Next Steps ................................................................................................................. 65

    API Version 2012-08-10

    iv

    Amazon DynamoDB Getting Started Guide

  • 7/24/2019 02.Amazon DynamoDB

    5/70

    Getting Started with Amazon

    DynamoDB

    Welcome to the Amazon DynamoDB Getting Started Guide. This guide contains hands-on tutorials tohelp you learn about Amazon DynamoDB.We strongly encourage you to review this guide in this order:

    Become familiar with the basic DynamoDB concepts on this page.

    Work through the Tutorial: Basic DynamoDB Operations (p. 3)section.This tutorial uses thedownloadable version of DynamoDB, including an interactive JavaScript shell.This lets you learn aboutthe DynamoDB API for free, without having to pay any fees for throughput, storage, or data transfer.

    If you want to write programs that leverage DynamoDB, work through one of the language-specifictutorials in this Getting Started Guide. The sample code in these tutorials can run against eitherDynamoDB Local or the Amazon DynamoDB web service.

    After you complete the exercises in this guide, we recommend that you read the Amazon DynamoDBDeveloper Guide. The Amazon DynamoDB Developer Guideprovides more in-depth information aboutDynamoDB, including sample code and best practices.

    Topics

    Introduction to DynamoDB Concepts (p. 1)

    Next Step (p. 2)

    Introduction to DynamoDB ConceptsThis section briefly introduces some of the basic DynamoDB concepts.This will help you as you follow

    steps in the tutorials.

    Tables

    Similar to other database management systems, DynamoDB stores data in tables. A tableis a collectionof data. For example, you could create a table named People, where you could store information about

    friends, family, or anyone else of interest. You could also have a Carstable to store information aboutvehicles that people drive.

    API Version 2012-08-10

    1

    Amazon DynamoDB Getting Started Guide

    Introduction to DynamoDB Concepts

    http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/
  • 7/24/2019 02.Amazon DynamoDB

    6/70

    Items

    Each table contains multiple items. An itemis a group of attributes that is uniquely identifiable among allof the other items. In a Peopletable, each item would represent one person. For a Carstable, eachitem represents one vehicle. Items are similar in many ways to rows, records, or tuples in relational

    database systems. In DynamoDB, there is no limit to the number of items that you can store in a table.

    Attributes

    Each item is composed of one or more attributes. An attributeis a fundamental data element, somethingthat does not need to be broken down any further. A Departmentitem might have attributes such asDepartmentID, Name, Manager, and so on. An item in a Peopletable could contain attributes such asPersonID, LastName, FirstName, and so on. Attributes in DynamoDB are similar in many ways to

    fields or columns in other database management systems.

    Primary Key

    When you create a table, in addition to the table name, you must specify the primary key of the table. As

    in other databases, a primary key in DynamoDB uniquely identifies each item in the table, so that no twoitems can have the same key. When you add, update, or delete an item in the table, you must specifythe primary key attribute values for that item. The key values are required; you cannot omit them.

    DynamoDB supports two different kinds of primary keys:

    Primary key consisting of a hash attributeThe primary key consists of a single attribute, which is called a hash attribute. Each item in the tableis uniquely identified by its hash attribute value.

    Primary key consisting of hash and range attributesThe primary key consists of two attributes.The first attribute is the hash attribute and the second oneis the range attribute. Each item in the table is uniquely identified by the combination of its hash andrange attribute values. It is possible for two items to have the same hash attribute value, but thosetwo items must have different range attribute values.

    Secondary Indexes

    In DynamoDB, you can read data in a table by providing primary key attribute values. If you want to readthe data using non-key attributes, you can use a secondary index to do this. After you create a secondaryindex on a table, you can read data from the index in much the same way as you do from the table. Byusing secondary indexes, your applications can use many different query patterns, in addition to accessingthe data by primary key values.

    For more information, see the following topics in the Amazon DynamoDB Developer Guide:

    Data Model Concepts - Tables, Items, and Attributes

    Primary Key Secondary Indexes

    Next StepTutorial: Basic DynamoDB Operations (p. 3)

    API Version 2012-08-10

    2

    Amazon DynamoDB Getting Started Guide

    Items

    http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.TableItemAttributehttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.PrimaryKeyhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.SecondaryIndexeshttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.SecondaryIndexeshttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.PrimaryKeyhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.TableItemAttribute
  • 7/24/2019 02.Amazon DynamoDB

    7/70

    Tutorial: Basic DynamoDB

    Operations

    In this tutorial, you will learn the basics of DynamoDB operations.You will do this using the downloadableversion of DynamoDB, running on your computer.

    This edition of DynamoDB includes an interactive JavaScript shell, where you can get hands-on experiencewith the DynamoDB API:

    To use the shell, you enter JavaScript code on the left side, and then click the play button arrow () to runthe code.The right side shows you the results.

    In this exercise you will create a table called Musicand perform various operations on it, including additems, modify items, and read items. This exercise provides JavaScript code snippets that you copy andpaste into the shell.

    API Version 2012-08-10

    3

    Amazon DynamoDB Getting Started Guide

  • 7/24/2019 02.Amazon DynamoDB

    8/70

    At the end of this tutorial, you will have gained hands-on experience with most of the DynamoDB APIoperations.

    Cost:Free.

    PrerequisitesBefore you begin this tutorial, you need to download and run DynamoDB. After that, you will be able toaccess the built-in JavaScript shell.

    Download and Run DynamoDB

    DynamoDB is available as an executable .jarfile. It will run on Windows, Linux, Mac OS X, and other

    platforms that support Java. Follow these steps to obtain e steps in this procedure to download and runDynamoDB on your computer.

    1. Download DynamoDB for free using one of these links:

    .tar.gzformat: http://dynamodb-local.s3-website-us-west-2.amazonaws.com/dynamodb_local_latest.tar.gz

    .zipformat: http://dynamodb-local.s3-website-us-west-2.amazonaws.com/dynamodb_local_latest.zip

    ImportantDynamoDBsupports the Java Runtime Engine (JRE) version 6.x or newer; it will not run onolder JRE versions.

    2. After you have downloaded the archive to your computer, extract the contents and copy the extracteddirectory to a location of your choice.

    3. To start DynamoDB, open a command prompt window, navigate to the directory where you extractedDynamoDBLocal.jar, and enter the following command:

    java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -

    sharedDb

    NoteDynamoDB uses port 8000 by default. If port 8000 is unavailable, this command will throwan exception.You can use the -portoption to specify a different port number. For acomplete list of DynamoDB runtime options, including -port, type this command:java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar

    -help

    If you need to stop DynamoDB, you can do so by pressing Ctrl-C.

    4. You can now access the built-in JavaScript shell.

    Important

    We recommend that you run the DynamoDB JavaScript shell on Firefox or Chrome. If yourun the JavaScript shell in other browsers, errors may occur.

    Open a web browser on your computer and go to the following URL: http://localhost:8000/shell

    Next Step

    Step 1: Create a Table (p. 5)

    API Version 2012-08-10

    4

    Amazon DynamoDB Getting Started Guide

    Prerequisites

    http://dynamodb-local.s3-website-us-west-2.amazonaws.com/dynamodb_local_latest.tar.gzhttp://dynamodb-local.s3-website-us-west-2.amazonaws.com/dynamodb_local_latest.tar.gzhttp://dynamodb-local.s3-website-us-west-2.amazonaws.com/dynamodb_local_latest.ziphttp://localhost:8000/shellhttp://localhost:8000/shellhttp://dynamodb-local.s3-website-us-west-2.amazonaws.com/dynamodb_local_latest.ziphttp://dynamodb-local.s3-website-us-west-2.amazonaws.com/dynamodb_local_latest.tar.gzhttp://dynamodb-local.s3-website-us-west-2.amazonaws.com/dynamodb_local_latest.tar.gz
  • 7/24/2019 02.Amazon DynamoDB

    9/70

    Step 1: Create a TableIn this step, you will create a table named Music.You will use the CreateTableAPI operation to do this.The primary key for the table will consist of two attributes that are both string type: Artist(hash key)

    and SongTitle(range key).

    1. Copy the following code and paste it into the left side of the DynamoDB JavaScript shell window.

    var params = {

    TableName : "Music",

    KeySchema: [

    { AttributeName: "Artist", KeyType: "HASH", },

    { AttributeName: "SongTitle", KeyType: "RANGE" }

    ],

    AttributeDefinitions: [

    { AttributeName: "Artist", AttributeType: "S" },

    { AttributeName: "SongTitle", AttributeType: "S" }

    ],

    ProvisionedThroughput: {ReadCapacityUnits: 1,

    WriteCapacityUnits: 1

    }

    };

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

    if (err)

    console.log(JSON.stringify(err, null, 2));

    else

    console.log(JSON.stringify(data, null, 2));

    });

    In the code, you specify the table name, its primary key attributes and their data types.TheProvisionedThroughputparameter is required; however, the downloadable version of DynamoDBignores it.

    2. Click the play button arrow to run the code, as shown in the following screen shot. The responsefrom DynamoDB; is shown in the right side of the window.

    API Version 2012-08-10

    5

    Amazon DynamoDB Getting Started Guide

    Step 1: Create a Table

  • 7/24/2019 02.Amazon DynamoDB

    10/70

    In the response, take note of the TableStatus. Its value should be ACTIVE.This indicates that theMusictable is ready for use.

    In the code snippet, note the following:

    The paramsobject holds the parameters for the corresponding DynamoDB API operation.

    The dynamodb.line invokes the operation, with the correct parameters. In the exampleabove, the operation is createTable.

    Next Step

    Step 2: Get Information About Tables (p. 6)

    Step 2: Get Information About TablesDynamoDB stores detailed metadata about your tables, such as table name, its primary key attributes,table status, and provisioned throughput settings. In this section you will retrieve information about themusic table using the DynamoDB DescribeTableoperation and also obtain a list of tables using theListTablesoperation.

    Topics

    Step 2.1: Retrieve a Table Description (p. 6) Step 2.2: Retrieve a List of Your Tables (p. 7)

    Next Step (p. 7)

    Step 2.1: Retrieve a Table Description

    Use the DynamoDB DescribeTableoperation to view details about a table.

    API Version 2012-08-10

    6

    Amazon DynamoDB Getting Started Guide

    Next Step

  • 7/24/2019 02.Amazon DynamoDB

    11/70

    1. Replace everything in the left side of the DynamoDB JavaScript shell window with the following code:

    var params = {

    TableName: "Music"

    };

    dynamodb.describeTable(params, function(err, data) {

    if (err)

    console.log(JSON.stringify(err, null, 2));

    else

    console.log(JSON.stringify(data, null, 2));

    });

    2. Click the play button arrow to run the code.The response from DynamoDB contains a completedescription of the table.

    Step 2.2: Retrieve a List of Your TablesUse the ListTablesAPI operation to list the names of all of your tables.This operation does not requireany parameters.

    1. Replace everything in the left side of the DynamoDB JavaScript shell window with the following code:

    var params = {};

    dynamodb.listTables(params, function(err, data) {

    if (err)

    console.log(JSON.stringify(err, null, 2));

    else

    console.log(JSON.stringify(data, null, 2));

    });

    2. Click the play button arrow to run the code.The response from DynamoDB contains just one tablecalled Music.

    Next Step

    Step 3: Write Items to the Table (p. 7)

    Step 3: Write Items to the TableWhen you write an item to a DynamoDB table, only the primary key attribute(s) are required. Other thanthe primary key, the table does not require a schema. In this section, you will write an item to a table(PutItemoperation), write an item conditionally, and also write multiple items in a single operation(BatchWriteItemoperation).

    Topics

    API Version 2012-08-10

    7

    Amazon DynamoDB Getting Started Guide

    Step 2.2: Retrieve a List of Your Tables

  • 7/24/2019 02.Amazon DynamoDB

    12/70

    Step 3.1: Write a Single Item (p. 8)

    Step 3.3: Write Multiple Items (p. 9)

    Next Step (p. 11)

    Step 3.1: Write a Single ItemUse the PutItemAPI operation to write an item.

    1. Replace everything in the left side of the DynamoDB JavaScript shell window with the following code:

    var params = {

    TableName: "Music",

    Item: {

    "Artist":"No One You Know",

    "SongTitle":"Call Me Today",

    "AlbumTitle":"Somewhat Famous",

    "Year": 2015,

    "Price": 2.14, "Genre": "Country",

    "Tags": {

    "Composers": [

    "Smith",

    "Jones",

    "Davis"

    ],

    "LengthInSeconds": 214

    }

    }

    };

    dynamodb.putItem(params, function(err, data) {

    if (err) console.log(JSON.stringify(err, null, 2));

    else

    console.log(JSON.stringify(data, null, 2));

    });

    2. Click the play button arrow to run the code. If the write is successful, the response will be an emptymap: {}

    Note the following about the item you just added:

    Artistand SongTitleare primary key attributes(hash and range attributes respectively). Both are

    of string type. Every item that you add to the table must have values for these attributes. Other attributes areAlbumTitle(string), Year(number), Price(number), Genre(string), and Tags

    (map).

    DynamoDB allows you to nestattributes within other attributes.The Tagsmap contains two nestedattributesComposers(list) and LengthInSeconds(number).

    Artist, SongTitle, AlbumTitle, Year, Price, Genre, and Tagsare top-level attributes, becausethey are not nested within any other attributes.

    API Version 2012-08-10

    8

    Amazon DynamoDB Getting Started Guide

    Step 3.1:Write a Single Item

  • 7/24/2019 02.Amazon DynamoDB

    13/70

    For more information, see Data Typesin the Amazon DynamoDB Developer Guide.

    Step 3.2: Perform a Conditional Write

    By default, PutItemdoes not check first to see if there is already an item with the same key, it simply

    overwrites any existing item. If you want to ensure that you do not overwrite an existing item, you can

    add a ConditionExpressionparameter. This is a logical condition that must be satisfied in order forthe write to succeed.

    In this step you will try to write the same item, but this time you will specify a condition to see whether anitem with the same primary key already exists. The write will fail, because there is already an item in thetable with the same primary key.

    1. Modify the paramsobject so that it looks like this:

    var params = {

    TableName: "Music",

    Item: {

    "Artist":"No One You Know",

    "SongTitle":"Call Me Today",

    "AlbumTitle":"Somewhat Famous",

    "Year": 2015,

    "Price": 2.14,

    "Genre": "Country",

    "Tags": {

    "Composers": [

    "Smith",

    "Jones",

    "Davis"

    ],

    "LengthInSeconds": 214

    }

    },

    "ConditionExpression": "attribute_not_exists(Artist) and attribute_not_exists(SongTitle)"

    };

    NoteThe only difference is the ConditionExpressionparameter.This will prevent you fromoverwriting the item. if there is already an item in the table with the same primary key values(No One You Know, Call Me Today).For more information, see Condition Expressionsin the Amazon DynamoDB DeveloperGuide.

    2. Click the play button arrow to run the code.

    The conditional write fails because the item already exists.

    Step 3.3:Write Multiple Items

    You can use the BatchWriteItemoperation to perform multiple writes in one step. The following codeadds several items, with the required primary key attributes, but different non-key attributes.

    1. Replace everything in the left side of the DynamoDB JavaScript shell window with the following code:

    API Version 2012-08-10

    9

    Amazon DynamoDB Getting Started Guide

    Step 3.3:Write Multiple Items

    http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.DataTypeshttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.DataTypes
  • 7/24/2019 02.Amazon DynamoDB

    14/70

    var params = {

    RequestItems: {

    "Music": [

    {

    PutRequest: {

    Item: {

    "Artist": "No One You Know",

    "SongTitle": "My Dog Spot",

    "AlbumTitle":"Hey Now",

    "Price": 1.98,

    "Genre": "Country",

    "CriticRating": 8.4

    }

    }

    },

    {

    PutRequest: {

    Item: {

    "Artist": "No One You Know",

    "SongTitle": "Somewhere Down The Road", "AlbumTitle":"Somewhat Famous",

    "Genre": "Country",

    "CriticRating": 8.4,

    "Year": 1984

    }

    }

    },

    {

    PutRequest: {

    Item: {

    "Artist": "The Acme Band",

    "SongTitle": "Still In Love",

    "AlbumTitle":"The Buck Starts Here",

    "Price": 2.47, "Genre": "Rock",

    "PromotionInfo": {

    "RadioStationsPlaying":[

    "KHCR", "KBQX", "WTNR", "WJJH"

    ],

    "TourDates": {

    "Seattle": "20150625",

    "Cleveland": "20150630"

    },

    "Rotation": "Heavy"

    }

    }

    }

    },{

    PutRequest: {

    Item: {

    "Artist": "The Acme Band",

    "SongTitle": "Look Out, World",

    "AlbumTitle":"The Buck Starts Here",

    "Price": 0.99,

    "Genre": "Rock"

    }

    API Version 2012-08-10

    10

    Amazon DynamoDB Getting Started Guide

    Step 3.3:Write Multiple Items

  • 7/24/2019 02.Amazon DynamoDB

    15/70

    }

    }

    ]

    }

    };

    dynamodb.batchWriteItem(params, function (err, data) {

    if (err)

    console.log(JSON.stringify(err, null, 2));

    else

    console.log(JSON.stringify(data, null, 2));

    });

    2. Click the play button arrow to run the code. If the batch write is successful, the response will containthe following:"UnprocessedItems": {}.This indicates that all of the items in the batch have beenwritten.

    Next StepStep 4: Read an Item Using Its Primary Key (p. 11)

    Step 4: Read an Item Using Its Primary KeyDynamoDB provides the GetItemoperation for retrieving one item at a time. You can retrieve an entireitem, or a subset of its attributes.

    DynamoDB supports the Map and List attribute types. These attribute types allow you to nest otherattributes within them, so that you can store complex documents in an item. You can use GetItemtoretrieve an entire document, or just some of the nested attributes within that document.

    Step 4.1: Read an Item Using GetItem

    Use the GetItemAPI operation to read an item. You must provide the primary key of the item you want.DynamoDB will then read the item directly from its physical location in the database.

    The following code reads an item from the Musictable by specifying the primary key.

    1. Replace everything in the left side of the DynamoDB JavaScript shell window with the following code:

    var params = {

    TableName: "Music",

    Key: { "Artist": "No One You Know",

    "SongTitle": "Call Me Today"

    }

    };

    dynamodb.getItem(params, function(err, data) {

    if (err)

    console.log(JSON.stringify(err, null, 2));

    API Version 2012-08-10

    11

    Amazon DynamoDB Getting Started Guide

    Next Step

  • 7/24/2019 02.Amazon DynamoDB

    16/70

    else

    console.log(JSON.stringify(data, null, 2));

    });

    2. Click the play button arrow to run the code.The requested item appears in the response.3. (Optional) You can change the primary key in the preceding code to retrieve different music items.

    Let us retrieve different music items from the table.

    Modify the paramsobject, using any of the primary key values shown below. Click the play buttonarrow to run the code, and verify that the correct item is returned in the response.

    Key: {

    "Artist": "No One You Know",

    "SongTitle": "My Dog Spot"

    }

    Key: {

    "Artist": "No One You Know",

    "SongTitle": "Somewhere Down The Road"

    }

    Key: {

    "Artist": "The Acme Band",

    "SongTitle": "Still In Love"

    }

    Key: {

    "Artist": "The Acme Band",

    "SongTitle": "Look Out, World"

    }

    Step 4.2: Retrieve a Subset of Attributes Using aProjection Expression

    By default, the GetItemAPI operation returns all of the attributes in the item. To return only some of the

    attributes, you provide a projection expression a comma-separated string of attribute names that youwant to use.

    1. In the DynamoDB JavaScript shell window, modify the paramsobject so that it looks like this:

    var params = {

    TableName: "Music",

    Key: {

    API Version 2012-08-10

    12

    Amazon DynamoDB Getting Started Guide

    Step 4.2: Retrieve a Subset of Attributes Using aProjection Expression

  • 7/24/2019 02.Amazon DynamoDB

    17/70

    "Artist": "No One You Know",

    "SongTitle": "Call Me Today"

    },

    ProjectionExpression: "AlbumTitle"

    };

    2. Click the play button arrow to run the code. Only one attribute (AlbumTitle) appears in the response.

    Handling Attribute Names that Are Also Reserved Words

    In DynamoDB, you have a great deal of flexibility when it comes to naming your tables and attributes.However, it is possible that a name you choose might conflict with a reserved word. In this situation, youcan define an expression attribute nameand use it in the projection expression.

    For the complete list, see Reserved Wordsin the Amazon DynamoDB Developer Guide.

    1. Modify the projection expression so that it also includes the Yearattribute, which is a reserved word

    and therefore the GetItemoperation will fail:

    var params = {

    TableName: "Music",

    Key: {

    "Artist": "No One You Know",

    "SongTitle": "Call Me Today"

    },

    ProjectionExpression: "AlbumTitle, Year"

    };

    2. Click the play button arrow to run the code. An error message appears in the response:

    Invalid ProjectionExpression: Attribute name is a reserved keyword; reservedkeyword: Year

    3. Modify the paramsobject to use a placeholder token (#y) in ProjectionExpression, and thendefine the placeholder in the ExpressionAttributeNamesparameter.

    var params = {

    TableName: "Music",

    Key: {

    "Artist": "No One You Know",

    "SongTitle": "Call Me Today"

    },

    ProjectionExpression: "AlbumTitle, #y",

    ExpressionAttributeNames: {"#y": "Year"}

    };

    In the ProjectionExpression, the word Yearis replaced by the token #y. The #(pound sign) isrequired, and indicates that this is a placeholder. The ExpressionAttributeNamesparameterindicates that #yis to be replaced by Yearat runtime.

    4. Click the play button arrow to run the code.The AlbumTitleand Yearattributes appear in the

    response.

    API Version 2012-08-10

    13

    Amazon DynamoDB Getting Started Guide

    Step 4.2: Retrieve a Subset of Attributes Using aProjection Expression

    http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html
  • 7/24/2019 02.Amazon DynamoDB

    18/70

    Step 4.3: Retrieve Nested Attributes Using Document PathNotation

    DynamoDB supports a map type attribute to store documents. In the Musictable, we use a map typeattribute called Tagsto store information such as list of music composers, song duration information, and

    so on.These are nested attributes.You can retrieve entire document, or a subset of these nested attributesby specifying document path notation.

    A document pathtells DynamoDB where to find the attribute, even if it is deeply nested within multiplelists and maps. In a document path, use the following operators to access nested attributes:

    For a list, use square brackets: [n], where nis the element number. List elements are zero-based, so[0] represents the first element in the list, [1] represents the second, and so on.

    For a map, use a dot: . The dot acts as a separator between elements in the map.

    1. Modify the paramsobject so that it looks like this:

    var params = {TableName: "Music",

    Key: {

    "Artist": "No One You Know",

    "SongTitle": "Call Me Today"

    },

    ProjectionExpression: "AlbumTitle, #y, Tags.Composers[0],

    Tags.LengthInSeconds",

    ExpressionAttributeNames: {"#y": "Year"}

    };

    2. Click the play button arrow to run the code.The response contains only the top-level and nestedattributes that were specified in ProjectionExpression.

    Step 4.4: Read Multiple Items Using BatchGetItem

    TheGetItemoperation retrieves a single item by its primary key. DynamoDB also supports BatchGetItemoperation for you to read multiple items in a single request. You specify a list of primary keys for thisoperation.

    The following example retrieves a group of music items. The example also specifies the optionalProjectionExpressionto retrieve only a subset of the attributes.

    1. Replace everything in the left side of the DynamoDB JavaScript shell window with the following code:

    var params = {

    RequestItems: {

    "Music": {

    Keys: [

    {

    "Artist": "No One You Know",

    "SongTitle": "My Dog Spot"

    },

    {

    API Version 2012-08-10

    14

    Amazon DynamoDB Getting Started Guide

    Step 4.4: Read Multiple Items Using BatchGetItem

  • 7/24/2019 02.Amazon DynamoDB

    19/70

    "Artist": "No One You Know",

    "SongTitle": "Somewhere Down The Road"

    },

    {

    "Artist": "The Acme Band",

    "SongTitle": "Still In Love"

    },

    {

    "Artist": "The Acme Band",

    "SongTitle": "Look Out, World"

    }

    ],

    ProjectionExpression:"PromotionInfo, CriticRating, Price"

    }

    }

    };

    dynamodb.batchGetItem(params, function (err, data) {

    if (err)

    console.log(JSON.stringify(err, null, 2));

    else console.log(JSON.stringify(data, null, 2));

    });

    2. Click the play button arrow to run the code.The response contains all of the attributes specified inProjectionExpression. If one of the items does not have an attribute, it appears in the response asan empty map: {}

    3. (Optional) Remove the ProjectionExpresionentirely, and retrieve all of the attributes from theitems.

    4. (Optional) Add a new ProjectionExpressionthat retrieves at least one nested attribute. Use

    document path notation to do this.

    Next Step

    Step 5: Query and Scan the Table (p. 15)

    Step 5: Query and Scan the TableDynamoDB supports the Queryoperation on tables whose primary key is composed of both hash andrange attributes.You can also filter query results.

    In addition, DynamoDB also supports the Scanoperation on a table.This section provides introductory

    examples of using these operations.

    Topics

    Step 5.1: Run a Query (p.16)

    Step 5.2: Filter Query Results (p. 17)

    Step 5.3: Scan the Table (p. 17)

    Next Step (p. 18)

    API Version 2012-08-10

    15

    Amazon DynamoDB Getting Started Guide

    Next Step

  • 7/24/2019 02.Amazon DynamoDB

    20/70

    Step 5.1: Run a Query

    This section provides examples of Query operations.The queries are specified against the Musictable.Remember, the table primary key is made of Artist(hash attribute) and Title(range attributes).

    Query using only the hash attribute of the primary key. For example, find songs by an artist.

    Query using both hash and range attributes of a primary key. For example, find songs by an artist andsong title starting with a specific string.

    Filter query results. Find songs by an artist and then return only those songs that have more than threeradio stations playing them.

    Query Using a Hash Key Attribute

    Follow these steps to query for songs by an artist. Note that you use the KeyConditionExpressionto specify the primary key. In this example it specifies only the hash attribute (Artist).

    1. Replace everything in the left side of the DynamoDB JavaScript shell window with the following code:

    var params = {

    TableName: "Music",

    KeyConditionExpression: "Artist = :artist",

    ExpressionAttributeValues: {

    ":artist": "No One You Know"

    }

    };

    dynamodb.query(params, function(err, data) {

    if (err)

    console.log(JSON.stringify(err, null, 2));

    else

    console.log(JSON.stringify(data, null, 2));

    });

    In the KeyConditionExpression, :artistis a token. The token value is provided in theExpressionAttributeValuesparameter.The :(colon) indicates that this is a placeholder forthe value.

    2. Click the play button arrow to run the code. Only the songs by the band No One You Knowarereturned.

    Query Using Hash and Range Key Attributes

    Follow these steps to query for songs by an ar tist (The Acme Band) with song title starting with a specific

    string (S). Note that you use the KeyConditionExpressionto specify the primary key. In this exampleit specifies both the hash and range attributes of the primary key.

    1. Modify the paramsobject from Query Using a Hash Key Attribute (p. 16)so that it looks like this:

    var params = {

    TableName: "Music",

    ProjectionExpression: "SongTitle",

    API Version 2012-08-10

    16

    Amazon DynamoDB Getting Started Guide

    Step 5.1: Run a Query

  • 7/24/2019 02.Amazon DynamoDB

    21/70

    KeyConditionExpression: "Artist = :artist and begins_with(SongTitle,

    :letter)",

    ExpressionAttributeValues: {

    ":artist": "The Acme Band",

    ":letter": "S"

    }

    };

    Note the use of ProjectionExpression, which will cause the query to return the SongTitle

    attribute only.

    2. Click the play button arrow to run the code. Only songs by The Acme Band, with titles that beginwith the letter S, are returned. (There is only one song that meets this criteria in the Musictable.)

    Step 5.2: Filter Query Results

    You can filter results of a query by adding the FilterExpressionparameter. In this example you specifya query to find songs by an artist (The Acme Band). The query also specifies the FilterExpressionto request DynamoDB to return only the song items that are being played on more than three radiostations.

    1. Modify the paramsobject from Query Using a Hash Key Attribute (p. 16)so that it looks like this:

    var params = {

    TableName: "Music",

    ProjectionExpression: "SongTitle, PromotionInfo.Rotation",

    KeyConditionExpression: "Artist = :artist",

    FilterExpression: "size(PromotionInfo.RadioStationsPlaying) >= :howmany",

    ExpressionAttributeValues: {

    ":artist": "The Acme Band",

    ":howmany": 3 },

    };

    Note the use of ProjectionExpression, which will cause the query to return the top-level SongTitleattribute and the nested PromotionInfo.Rotationattribute.

    Also the FilterExpression specifies the size() function. For a list of predefined functions, go to theExpression Referencein the Amazon DynamoDB Developer Guide.

    2. Click the play button arrow to run the code.The response contains the only song by The AcmeBand that is in heavy rotation on at least three radio stations.

    Step 5.3: Scan the TableYou can use the Scanoperation to retrieve all of the items in a table. In the following example you scanthe Musictable.

    1. Replace everything in the left side of the DynamoDB JavaScript shell window with the following code:

    API Version 2012-08-10

    17

    Amazon DynamoDB Getting Started Guide

    Step 5.2: Filter Query Results

    http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html
  • 7/24/2019 02.Amazon DynamoDB

    22/70

    var params = {

    TableName: "Music"

    };

    dynamodb.scan(params, function(err, data) {

    if (err)

    console.log(JSON.stringify(err, null, 2));

    else

    console.log(JSON.stringify(data, null, 2));

    });

    2. Click the play button arrow to run the code. All of the table items appear in the response.

    Next Step

    Step 6:Work with a Secondary Index (p. 18)

    Step 6:Work with a Secondary IndexWithout an index, you can query for items based on primary key.You can add indexes to your tabledepending on your query patterns. DynamoDB supports two different kinds of indexes:

    Global secondary index an index with a hash and range key that can be different from those on thetable.You can create or delete a global secondary index on a table at any time.

    Local secondary index an index that has the same hash key attribute as the primary key of the table,but a different range key.You can only create a local secondary index when you create a table; whenyou delete the table, the local secondary index is also deleted.

    For more information about these indexes, go to Improving Data Access with Secondary Indexes inDynamoDBin the Amazon DynamoDB Developer Guide.

    In this step, you will add a secondary index to the Musictable.You will then query and scan the index,

    in the same way as you would query or scan a table. In this tutorial, you will create and use a globalsecondary index.

    Topics

    Step 6.1: Create a Global Secondary Index (p.18)

    Step 6.2: Query the Index (p. 20)

    Step 6.3: Scan the Index (p. 20)

    Next Step (p. 21)

    Step 6.1: Create a Global Secondary Index

    The Musictable has a primary key made of Artist(hash attribute) and SongTitle(range attribute).Now suppose you want to query this table by Genreand find all of the Countrysongs. Searching onthe primary key will help in this case. To do this, we will build a secondary index with Genreas the hashattribute.

    API Version 2012-08-10

    18

    Amazon DynamoDB Getting Started Guide

    Next Step

    http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SecondaryIndexes.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SecondaryIndexes.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SecondaryIndexes.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SecondaryIndexes.html
  • 7/24/2019 02.Amazon DynamoDB

    23/70

    To make this interesting, we will add the Priceattribute as the range key. So you can now run a queryto find all Countrysongs with Priceless than 0.99.

    You can add an index at the time that you create a table or later using the UpdateTableoperation.

    1. Replace everything in the left side of the DynamoDB JavaScript shell window with the following code:

    var params = {

    TableName: "Music",

    AttributeDefinitions:[

    {AttributeName: "Genre", AttributeType: "S"},

    {AttributeName: "Price", AttributeType: "N"}

    ],

    GlobalSecondaryIndexUpdates: [

    {

    Create: {

    IndexName: "GenreAndPriceIndex",

    KeySchema: [

    {AttributeName: "Genre", KeyType: "HASH"},

    {AttributeName: "Price", KeyType: "RANGE"}, ],

    Projection: {

    "ProjectionType": "ALL"

    },

    ProvisionedThroughput: {

    "ReadCapacityUnits": 1,"WriteCapacityUnits": 1

    }

    }

    }

    ]

    };

    dynamodb.updateTable(params, function(err, data) {

    if (err)

    console.log(JSON.stringify(err, null, 2));

    else

    console.log(JSON.stringify(data, null, 2));

    });

    In the code:

    AttributeDefinitionslists data types of attributes that are later defined as hash and rangeattributes of the index.

    GlobalSecondaryIndexUpdatesspecifies the index operations.You can create index, update

    index, or delete an index.

    The ProvisionedThroughputparameter is required, but the downloadable version of DynamoDBignores it.

    2. Click the play button arrow to run the code.

    In the response, take note of the IndexStatus. Its value should be CREATING, which indicates thatthe index is being built. The new should be available for use within a few seconds.

    API Version 2012-08-10

    19

    Amazon DynamoDB Getting Started Guide

    Step 6.1: Create a Global Secondary Index

  • 7/24/2019 02.Amazon DynamoDB

    24/70

    Step 6.2: Query the Index

    Now we will use the index to query for all Countrysongs.The index has all of the data you need, so youquery the index and not the table.

    You use the same Queryoperation to query a table (see Step 5: Query and Scan the Table (p. 15)) oran index on the table. When you query an index you specify both the table name and the index name.

    1. Replace everything in the left side of the DynamoDB JavaScript shell window with the following code:

    var params = {

    TableName: "Music",

    IndexName: "GenreAndPriceIndex",

    KeyConditionExpression: "Genre = :genre",

    ExpressionAttributeValues: {

    ":genre": "Country"

    },

    ProjectionExpression: "SongTitle, Price"

    };

    dynamodb.query(params, function(err, data) {

    if (err)

    console.log(JSON.stringify(err, null, 2));

    else

    console.log(JSON.stringify(data, null, 2));

    });

    2. Click the play button arrow to run the code. Only the Countrysongs are returned.

    3. Now let us query forCountrysongs that cost more than two dollars. Here you specify both the hashand range key values for index. Modify the paramsobject so that it looks like this:

    var params = {

    TableName: "Music",

    IndexName: "GenreAndPriceIndex",

    KeyConditionExpression: "Genre = :genre and Price > :price",

    ExpressionAttributeValues: {

    ":genre": "Country",

    ":price": 2.00

    },

    ProjectionExpression: "SongTitle, Price"

    };

    4. Click the play button arrow to run the code.This query uses both of the index key attributes (Genreand Price), returning only the Countrysongs that cost more than 2.00.

    Step 6.3: Scan the Index

    You can scan an index (using the Scanoperation) in the same way that you scan a table.When scanningan index, you provide both the table name and index name.

    API Version 2012-08-10

    20

    Amazon DynamoDB Getting Started Guide

    Step 6.2: Query the Index

  • 7/24/2019 02.Amazon DynamoDB

    25/70

    In this example, we will scan the entire global secondary index you created, but we'll retrieve specificattributes only.

    1. Replace everything in the left side of the DynamoDB JavaScript shell window with the following code:

    var params = { TableName: "Music",

    IndexName: "GenreAndPriceIndex",

    ProjectionExpression: "Genre, Price, SongTitle, Artist, AlbumTitle"

    };

    dynamodb.scan(params, function(err, data) {

    if (err)

    console.log(JSON.stringify(err, null, 2));

    else

    console.log(JSON.stringify(data, null, 2));

    });

    2. Click the play button arrow to run the code. All of the items in the index are returned.

    3. (Optional) Note that there are only four items in the index (Count), but there are five items in the

    table.The reason is that one of the items does not have a Priceattribute, so that item was notincluded in GenreAndPriceIndex.

    Which of the songs in Musicitems does not have a Priceattribute? Can you determine which oneit is?

    Next Step

    Step 7: Modify Items in the Table (p. 21)

    Step 7: Modify Items in the TableYou can modify an item in a table using UpdateItemor you can delete an item using the DeleteItemoperations.You can update item by updating values of existing attributes, add new attributes, or removeexisting attributes.You can use keywords in the UpdateItemoperation such as Setand Removetorequest specific updates.

    Topics

    Step 7.1: Update an Item (p. 21)

    Step 7.2: Delete an Item (p. 24)

    Next Step (p. 25)

    Step 7.1: Update an Item

    The UpdateItemAPI operation lets you do the following:

    Add more attributes to an item.

    Modify the values of one or more attributes in the item.

    Remove attributes from the item.

    API Version 2012-08-10

    21

    Amazon DynamoDB Getting Started Guide

    Next Step

  • 7/24/2019 02.Amazon DynamoDB

    26/70

    To specify which operations to perform, you use an update expression. An update expressionis a stringcontaining attribute names, operation keywords (such as SETand REMOVE), and new attribute values.You can combine multiple updates in a single update expression.

    For more information, see Reserved Wordsin the Amazon DynamoDB Developer Guide.

    By default, UpdateItemoperation does not return any data (empty response).You can optionally specifythe ReturnValuesparameter to request attribute values as they appeared before or after the update:

    ALL_OLDreturns all attribute values as they appeared before the update.

    UPDATED_OLDreturns only the updated attributes as they appeared before the update.

    ALL_NEWreturns all attribute values as they appear after the update.

    UPDATED_NEWreturns only the updated attributes as they appeared after the update.

    In this example, you will perform a couple of updates to an item in the Musictable.

    1. The following example updates a Musictable item by adding a new RecordLabelattribute usingthe UpdateExpressionparameter.

    Replace everything in the left side of the DynamoDB JavaScript shell window with the following code:

    var params = {

    TableName: "Music",

    Key: {

    "Artist":"No One You Know",

    "SongTitle":"Call Me Today"

    },

    UpdateExpression: "SET RecordLabel = :label",

    ExpressionAttributeValues: {

    ":label": "Global Records"

    },

    ReturnValues: "ALL_NEW"

    };

    dynamodb.updateItem(params, function(err, data) {

    if (err)

    console.log(JSON.stringify(err, null, 2));

    else

    console.log(JSON.stringify(data, null, 2));

    });

    2. Click the play button arrow to run the code.Verify that the item in the response has a RecordLabel

    attribute.

    3. We will now apply multiple changes to the item using the UpdateExpressionparameter: Change

    the price, and remove one of the composers.

    Modify the paramsobject so that it looks like this:

    var params = {

    TableName: "Music",

    Key: {

    "Artist":"No One You Know",

    API Version 2012-08-10

    22

    Amazon DynamoDB Getting Started Guide

    Step 7.1: Update an Item

    http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.Modifying.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.Modifying.html
  • 7/24/2019 02.Amazon DynamoDB

    27/70

    "SongTitle":"Call Me Today"

    },

    UpdateExpression:

    "SET Price = :price REMOVE Tags.Composers[2]",

    ExpressionAttributeValues: {

    ":price": 0.89

    },

    ReturnValues: "ALL_NEW"

    };

    4. Click the play button arrow to run the code. Verify that the UpdateExpressionworked.

    Specify a Conditional Write

    By default updates are performed unconditionally.You can specify a condition in the UpdateItemoperation to perform conditional update. For example, you may want to check if an attribute exists beforechanging its value, or check the existing value and apply an update only if the existing value meets certaincriteria.

    The UpdateItemoperation provides ConditionExpressionparameter for you to specify one or moreconditions.

    In this example, you add an attribute only if it doesn't already exist.

    1. Modify the paramsobject from Step 7.1: Update an Item (p. 21)so that it looks like this:

    var params = {

    TableName: "Music",

    Key: {

    "Artist":"No One You Know",

    "SongTitle":"Call Me Today"

    }, UpdateExpression: "SET RecordLabel = :label",

    ExpressionAttributeValues: {

    ":label": "New Wave Recordings, Inc."

    },

    ConditionExpression: "attribute_not_exists(RecordLabel)",

    ReturnValues: "ALL_NEW"

    };

    2. Click the play button arrow to run the code. This should fail with response:The conditionalrequest failed, because the item already has the RecordLabelattribute.

    Specify an Atomic CounterDynamoDB supports atomic counters, where you use the UpdateItemoperation to increment or decrementthe value of an existing attribute without interfering with other write requests. (All write requests are appliedin the order in which they were received.) For example, a music player application might want to maintaina counter each time song is played. In this case, the application would need to increment this counterregardless of its current value. For more information, go to Atomic Countersin the Amazon DynamoDBDeveloper Guide.

    API Version 2012-08-10

    23

    Amazon DynamoDB Getting Started Guide

    Step 7.1: Update an Item

    http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.AtomicCountershttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.AtomicCounters
  • 7/24/2019 02.Amazon DynamoDB

    28/70

    In this example we will first use the UpdateItemoperation to add an attribute (Plays) to keep track ofthe number of times the song is played. Then, using another UpdateItemoperation, we will incrementits value by 1.

    1. Modify the paramsobject from Step 7.1: Update an Item (p. 21)so that it looks like this:

    var params = {

    TableName: "Music",

    Key: {

    "Artist":"No One You Know",

    "SongTitle":"Call Me Today"

    },

    UpdateExpression: "SET Plays = :val",

    ExpressionAttributeValues: {

    ":val": 0

    },

    ReturnValues: "UPDATED_NEW"

    };

    2. Click the play button arrow to run the code.The Playsattribute is added, and its value (zero) isshown in the response.

    3. Now modify the paramsobject so that it looks like this:

    var params = {

    TableName: "Music",

    Key: {

    "Artist":"No One You Know",

    "SongTitle":"Call Me Today"

    },

    UpdateExpression: "SET Plays = Plays + :incr",

    ExpressionAttributeValues: {

    ":incr": 1

    },

    ReturnValues: "UPDATED_NEW"

    };

    4. Click the play button arrow to run the code.The Playsattribute is incremented by one.

    5. Run the code a few more times. Each time you do this, Playsis incremented.

    Step 7.2: Delete an Item

    You will now use the DeleteItemAPI operation to delete an item from the table. Note that this operation

    is permanentthere is no way to restore an item.

    1. Replace everything in the left side of the DynamoDB JavaScript shell window with the following code:

    var params = {

    TableName: "Music",

    Key: {

    Artist: "The Acme Band",

    API Version 2012-08-10

    24

    Amazon DynamoDB Getting Started Guide

    Step 7.2: Delete an Item

  • 7/24/2019 02.Amazon DynamoDB

    29/70

    SongTitle: "Look Out, World"

    }

    };

    dynamodb.deleteItem(params, function(err, data) {

    if (err)

    console.log(JSON.stringify(err, null, 2));

    else

    console.log(JSON.stringify(data, null, 2));

    });

    2. Click the play button arrow to run the code. The item is deleted.

    Specify a Conditional Delete

    By default, a delete operation is unconditional. However, you can use the ConditionExpressionparameter to perform conditional deletes. In this example you delete an item, only if its price is 0.

    1. Modify the paramsobject so that it looks like this:

    var params = {

    TableName: "Music",

    Key: {

    Artist: "No One You Know",

    SongTitle: "My Dog Spot"

    },

    ConditionExpression: "Price = :price",

    ExpressionAttributeValues: {

    ":price": 0.00

    }

    };

    2. Click the play button arrow to run the code.The conditional delete fails because the song is notfree (Priceis not 0.00).

    Next Step

    Step 8: Clean Up (p. 25)

    Step 8: Clean UpIn this step, you will use the DeleteTableAPI operation to remove the table.When you do this, theMusictable, GenreAndPriceIndex, and all of the data will be permanently deleted. This operationcannot be undone.

    To delete the table

    1. Replace everything in the left side of the DynamoDB JavaScript shell window with the following code:

    API Version 2012-08-10

    25

    Amazon DynamoDB Getting Started Guide

    Next Step

  • 7/24/2019 02.Amazon DynamoDB

    30/70

    var params = {

    TableName: "Music"

    };

    dynamodb.deleteTable(params, function(err, data) {

    if (err)

    console.log(JSON.stringify(err, null, 2));

    else

    console.log(JSON.stringify(data, null, 2));

    });

    2. Click the play button arrow to run the code to delete the table.

    The table is deleted immediately.

    Next Step

    Summary (p.26)

    SummaryIn this exercise, you downloaded DynamoDB and used the built-in JavaScript shell to learn about variousDynamoDB API operations.To learn more, see the following topics in the Amazon DynamoDB DeveloperGuide:

    Working With Tables

    Working With Items

    Query and Scan Secondary Indexes

    Best Practices

    Next Steps

    For an additional getting-started exercise, work through one of our programming-language specific tutorials:

    Tutorial: Java and DynamoDB (p. 47)

    Tutorial: Node.js and DynamoDB (p. 27)

    API Version 2012-08-10

    26

    Amazon DynamoDB Getting Started Guide

    Next Step

    http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTableshttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SecondaryIndexes.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BestPractices.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BestPractices.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SecondaryIndexes.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTableshttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/
  • 7/24/2019 02.Amazon DynamoDB

    31/70

    Tutorial: Node.js and DynamoDB

    In this tutorial, you will use the AWS SDK for JavaScript in Node.js to write simple programs to perform

    the following Amazon DynamoDB operations:

    Create a table called Moviesand load sample data in JSON format.

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

    Run simple queries.

    You will use the downloadable version of DynamoDB in this tutorial. In the Summary (p.44), we willexplain how to run the same code against the DynamoDB web service.

    Cost:Free

    PrerequisitesBefore you begin this tutorial, you will need to do the following:

    Download and run DynamoDB on your computer. For more information, see Download and RunDynamoDB (p. 4).

    Sign up for Amazon Web Services and create access keys (access key ID and secret access key).You need these credentials to use the AWS SDKs. For sign up instructions, go to http://aws.amazon.com.

    Create an AWS credentials file to store your access keys. For more information, see Shared CredentialsFilein the AWS SDK for JavaScript in Node.js Getting Started Guide.

    Set up the AWS SDK for JavaScript in Node.js.You need to do the following:

    Go to http://nodejs.organd install Node.js.

    Go to http://aws.amazon.com/sdk-for-node-jsand install the AWS SDK for JavaScript in Node.js.

    For more information, see the AWS SDK for JavaScript in Node.js Getting Started Guide.

    TipAs you work through this tutorial, you can refer to the AWS SDK for JavaScript in Node.js APIReference.

    We also recommend you review the DynamoDB concepts. For more information, see Introduction toDynamoDB Concepts (p. 1).

    API Version 2012-08-10

    27

    Amazon DynamoDB Getting Started Guide

    Prerequisites

    http://aws.amazon.com/http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html#Credentials_from_the_Shared_Credentials_File_____aws_credentials_http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html#Credentials_from_the_Shared_Credentials_File_____aws_credentials_http://nodejs.org/http://aws.amazon.com/sdk-for-node-jshttp://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-intro.htmlhttp://docs.aws.amazon.com/AWSJavaScriptSDK/latest/frames.htmlhttp://docs.aws.amazon.com/AWSJavaScriptSDK/latest/frames.htmlhttp://docs.aws.amazon.com/AWSJavaScriptSDK/latest/frames.htmlhttp://docs.aws.amazon.com/AWSJavaScriptSDK/latest/frames.htmlhttp://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-intro.htmlhttp://aws.amazon.com/sdk-for-node-jshttp://nodejs.org/http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html#Credentials_from_the_Shared_Credentials_File_____aws_credentials_http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html#Credentials_from_the_Shared_Credentials_File_____aws_credentials_http://aws.amazon.com/
  • 7/24/2019 02.Amazon DynamoDB

    32/70

    Next Step

    Step 1: Create a Table (p. 28)

    Step 1: Create a TableIn this step, you will create a table named Movies. The primary key for the table is composed of thefollowing hash and range attributes:

    yearthe hash attribute of number type.

    titlethe range attribute of string type.

    1. Copy the following program into a file named MoviesCreateTable.js.

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

    AWS.config.update({

    region: "us-west-2", endpoint: "http://localhost:8000"

    });

    var dynamodb = new AWS.DynamoDB();

    var params = {

    TableName : "Movies",

    KeySchema: [

    { AttributeName: "year", KeyType: "HASH"},

    { AttributeName: "title", KeyType: "RANGE" }

    ],

    AttributeDefinitions: [

    { AttributeName: "year", AttributeType: "N" },

    { AttributeName: "title", AttributeType: "S" } ],

    ProvisionedThroughput: {

    ReadCapacityUnits: 10,

    WriteCapacityUnits: 10

    }

    };

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

    if (err) {

    console.error("Unable to create table. Error JSON:", JSON.stringi

    fy(err, null, 2));

    } else {

    console.log("Created table. Table description JSON:", JSON.stringi

    fy(data, null, 2)); }

    });

    Note

    You set the endpoint (client.setEndpoint) to indicate that you are creating the tablein DynamoDB on your computer.

    In the createTablecall, you specify table name, primary key attributes, and its datatypes.

    API Version 2012-08-10

    28

    Amazon DynamoDB Getting Started Guide

    Step 1: Create a Table

  • 7/24/2019 02.Amazon DynamoDB

    33/70

    The ProvisionedThroughputparameter is required; however, the downloadable versionof DynamoDB ignores it. (Provisioned throughput is beyond the scope of this exercise.)

    2. Type the following command to run the program:

    node MoviesCreateTable.js

    Next Step

    Step 2: Load Sample Data (p. 29)

    Step 2: Load Sample DataIn this step, you will populate the Moviestable with sample data.

    Topics

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

    Step 2.2: Load the Sample Data Into the Movies Table (p. 30)

    We will use a sample data file containing information from a few thousand movies from the Internet MovieDatabase (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:

    We use the yearand titleas the primary key attribute values for our Moviestable.

    We store the rest of theinfovalues in a single attribute called infoin our Moviestable, this attribute

    will be of DynamoDB map type. This illustrates how you can store JSON in a DynamoDB attribute.

    The following is an example of movie data:

    {

    "year" : 2013,

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

    API Version 2012-08-10

    29

    Amazon DynamoDB Getting Started Guide

    Step 2: Load Sample Data

  • 7/24/2019 02.Amazon DynamoDB

    34/70

    "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/O9ER

    WAU7FS797AJ7LU8HN09AMUP908RLlo5JF90EWR7LJKQ7@@._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) using this link:

    moviedata.zip

    2. Extract the data file (moviedata.json) from the archive.

    3. Copy the data file (moviedata.json) to your current directory.

    Step 2.2: Load the Sample Data Into the MoviesTable

    After you have downloaded the sample data, you can run the following program to populate the Moviestable.

    1. Copy the following program into a file named MoviesLoadData.js:

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

    var fs = require('fs');

    AWS.config.update({

    region: "us-west-2",

    endpoint: "http://localhost:8000"

    });

    var dynamodbDoc = new AWS.DynamoDB.DocumentClient();

    API Version 2012-08-10

    30

    Amazon DynamoDB Getting Started Guide

    Step 2.1: Download the Sample Data File

    http://localhost/var/www/apps/conversion/tmp/scratch_2/samples/moviedata.ziphttp://localhost/var/www/apps/conversion/tmp/scratch_2/samples/moviedata.zip
  • 7/24/2019 02.Amazon DynamoDB

    35/70

    console.log("Importing movies into DynamoDB. Please wait.");

    var allMovies = JSON.parse(fs.readFileSync('moviedata.json', 'utf8'));

    allMovies.forEach(function(movie) {

    var params = {

    TableName: "Movies",

    Item: {

    "year": movie.year,

    "title": movie.title,

    "info": movie.info

    }

    };

    dynamodbDoc.put(params, function(err, data) {

    if (err) {

    console.error("Unable to add movie", movie.title, ". Error JSON:",

    JSON.stringify(err, null, 2));

    } else {

    console.log("PutItem succeeded:", movie.title);

    }

    });});

    NoteUsing the AWS.DynamoDB.DocumentClientis the easiest way to create, read, update,or delete data in an existing table. In this example, dynamodbDoc.putperforms the low-levelPutItemoperation.

    2. Type the following command to run the program:

    node MoviesLoadData.js

    Next Step

    Step 3: Put, Update, and Delete an Item (p. 31)

    Step 3: Put, Update, and Delete an ItemIn this step, you will perform various operations on the items in the Moviestable.You will run a Node.jsprogram that demonstrates several operations on items in the table.

    Step 3.1: Add a New Item (PutItem)

    In this step you add a new item to the Moviestable.

    1. Copy the following program into a file named MoviesItemOps01.js:

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

    AWS.config.update({

    region: "us-west-2",

    endpoint: "http://localhost:8000"

    });

    API Version 2012-08-10

    31

    Amazon DynamoDB Getting Started Guide

    Step 3: Put, Update, and Delete an Item

  • 7/24/2019 02.Amazon DynamoDB

    36/70

    var dynamodbDoc = 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":"Something happens."

    }

    }

    };

    console.log("Adding a new item...");

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

    }

    });

    NoteThe primary key is required.This code adds an item that will have primary key (year,title), and infoattributes. The infoattribute stores sample JSON that provides more

    information about the movie.Using the AWS.DynamoDB.DocumentClientis the easiest way to create, read, update,

    or delete data in an existing table. In this example, dynamodbDoc.putperforms the low-levelPutItemoperation.

    2. Type the following command to run the program:

    node MoviesItemOps01.js

    Step 3.2: Add an Item, Specify Condition (PutItem)

    By default, the PutItemoperation replaces any existing item with a new item. The DynamoDB PutItem

    operation provides ConditionExpressionto help you avoid overwriting an existing item. At present,the following item exists in the table. For details about PutItem, see PutItemin the Amazon DynamoDBAPI Reference.

    {

    year: 2015,

    title: "The Big New Movie",

    info: {

    plot: "Something happens." }

    }

    The code attempts to overwrite the item as follows:

    API Version 2012-08-10

    32

    Amazon DynamoDB Getting Started Guide

    Step 3.2: Add an Item, Specify Condition (PutItem)

    http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html
  • 7/24/2019 02.Amazon DynamoDB

    37/70

    {

    year: 2015,

    title: "The Big New Movie",

    info: {

    plot: "Nothing happens at all.",

    rating: 0

    }

    }

    For illustration, the PutItemoperation in the following example specifies a condition that checks forexistence of a primary key and it will fail because the primary key exists.

    1. Copy the following program into a file named MoviesItemOps02.js:

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

    AWS.config.update({

    region: "us-west-2",

    endpoint: "http://localhost:8000"

    });

    var dynamodbDoc = new AWS.DynamoDB.DocumentClient()

    var table = "Movies";

    var year = 2015;

    var title = "The Big New Movie";

    // Attempt a conditional write. We expect this to fail.

    var params = {

    TableName:table,

    Item:{

    "year": year, "title": title,

    "info":{

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

    "rating": 0.0

    }

    },

    ConditionExpression: "#yr :yyyy and title :t",

    ExpressionAttributeNames:{"#yr":"year"},

    ExpressionAttributeValues:{

    ":yyyy":year,

    ":t":title

    }

    };

    console.log("Attempting a conditional write...");

    dynamodbDoc.put(params, function(err, data) {

    if (err) {

    console.error("Unable to put item. Error JSON:", JSON.stringify(err,

    null, 2));

    } else {

    console.log("PutItem succeeded:", JSON.stringify(data, null, 2));

    }

    });

    API Version 2012-08-10

    33

    Amazon DynamoDB Getting Started Guide

    Step 3.2: Add an Item, Specify Condition (PutItem)

  • 7/24/2019 02.Amazon DynamoDB

    38/70

    NoteUsing the AWS.DynamoDB.DocumentClientis the easiest way to create, read, update,or delete data in an existing table. In this example, dynamodbDoc.putperforms the low-levelPutItemoperation.

    2. Type the following command to run the program:

    node MoviesItemOps02.js

    The program should fail with the following message:

    The conditional request failed

    3. Remove the ConditionExpressionparameter in the preceding code so that the paramslook asshown in the following code example to overwrite the item:

    var params = {

    TableName:table,

    Item:{

    "title": title,

    "year": year,

    "info":{

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

    "rating": 0.0

    }

    }

    };

    4. Run the program again. The putItemoperation should now succeed.

    Step 3.3: Update the Item (UpdateItem)

    You can use the DynamoDB UpdateItemoperation to modify an existing item. You can update valuesof existing attributes, add new attributes, or remove attributes in an UpdateItemoperation. For detailsabout UpdateItem, see UpdateItemin the Amazon DynamoDB API Reference.

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

    The item will change from:

    {

    year: 2015, title: "The Big New Movie",

    info: {

    plot: "Nothing happens at all.",

    rating: 0

    }

    }

    To the following:

    API Version 2012-08-10

    34

    Amazon DynamoDB Getting Started Guide

    Step 3.3: Update the Item (UpdateItem)

    http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html
  • 7/24/2019 02.Amazon DynamoDB

    39/70

    {

    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 into a file named MoviesItemOps03.js:

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

    AWS.config.update({

    region: "us-west-2",

    endpoint: "http://localhost:8000"

    });

    var dynamodbDoc = 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...");

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

    }

    });

    API Version 2012-08-10

    35

    Amazon DynamoDB Getting Started Guide

    Step 3.3: Update the Item (UpdateItem)

  • 7/24/2019 02.Amazon DynamoDB

    40/70

    NoteThis program uses UpdateExpressionto describe all updates you want to perform on thespecified item.The the updated attributes ("UPDATED_NEW").

    Using the AWS.DynamoDB.DocumentClientis the easiest way to create, read, update,or delete data in an existing table. In this example, dynamodbDoc.updateperforms thelow-level UpdateItemoperation.

    2. Type the following command to run the program:

    node MoviesItemOps03.js

    Step 3.4: Increment an Atomic Counter

    (UpdateItem)

    DynamoDB supports atomic counters, where you use the UpdateItemoperation to increment or decrementthe value of an existing attribute without interfering with other write requests. (All write requests are appliedin the order in which they were received.) For example, a music player application might want to maintaina counter each time song is played. In this case, the application would need to increment this counter

    regardless of its current value. For more information, see Atomic Countersin the Amazon DynamoDBDeveloper Guide. For details about UpdateItem, see UpdateItemin the Amazon DynamoDB APIReference.

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

    1. Copy the following program into a file named MoviesItemOps04.js:

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

    AWS.config.update({

    region: "us-west-2",

    endpoint: "http://localhost:8000"

    });

    var dynamodbDoc = 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"

    };

    API Version 2012-08-10

    36

    Amazon DynamoDB Getting Started Guide

    Step 3.4: Increment an Atomic Counter (UpdateItem)

    http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.AtomicCountershttp://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.AtomicCounters
  • 7/24/2019 02.Amazon DynamoDB

    41/70

    console.log("Updating the item...");

    dynamodbDoc.update(params, function(err, data) {

    if (err) {

    console.error("Unable to update item. Error JSON:", JSON.stringi

    fy(err, null, 2));

    } else {

    console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2));

    }

    });

    NoteUsing the AWS.DynamoDB.DocumentClientis the easiest way to create, read, update,or delete data in an existing table. In this example, dynamodbDoc.updateperforms the

    low-level UpdateItemoperation.

    2. Type the following command to run the program:

    node MoviesItemOps04.js

    Step 3.5: Update Item with a Condition(UpdateItem)

    The following program shows how to use UpdateItemwith a condition. If the condition evaluates to true,the update succeeds; otherwise, the update is not performed. In this case, the item is only updated ifthere are more than three actors. For details about UpdateItem, see UpdateItemin the Amazon

    DynamoDB API Reference.

    1. Copy the following program into a file named MoviesItemOps05.js:

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

    AWS.config.update({

    region: "us-west-2",

    endpoint: "http://localhost:8000"

    });

    var dynamodbDoc = 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:{

    API Version 2012-08-10

    37

    Amazon DynamoDB Getting Started Guide

    Step 3.5: Update Item with a Condition (UpdateItem)

    http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html
  • 7/24/2019 02.Amazon DynamoDB

    42/70

    ":num":3

    },

    ReturnValues:"UPDATED_NEW"

    };

    console.log("Attempting a conditional update...");

    dynamodbDoc.update(params, function(err, data) {

    if (err) {

    console.error("Unable to update item. Error JSON:", JSON.stringi

    fy(err, null, 2));

    } else {

    console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2));

    }

    });

    NoteUsing the AWS.DynamoDB.DocumentClientis the easiest way to create, read, update,or delete data in an existing table. In this example, dynamodbDoc.updateperforms the

    low-level UpdateItemoperation.2. Type the following command to run the program:

    node MoviesItemOps05.js

    The program should fail, because the movie has only three actors and the condition is checking forgreater than three actors, with the following message:

    The conditional request failed

    3. Modify the program so that ConditionExpressionlooks like this:

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

    The condition is now greater than or equal to 3instead of greater than 3.

    4. Run the program again. The updateItemoperation should now succeed.

    Step 3.6: Delete an Item (DeleteItem)

    You can use the DeleteItemoperation to delete one item by specifying its primary key.You can optionallyspecify a condition in the DeleteItemrequest to prevent item deletion based on a specified condition.In this following example, you will attempt to delete a specific movie item if its rating is 5.0 or less. Fordetails about DeleteItem, see DeleteItemin the Amazon DynamoDB API Reference.

    1. Copy the following program into a file named MoviesItemOps06.js:

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

    AWS.config.update({

    region: "us-west-2",

    endpoint: "http://localhost:8000"

    });

    var dynamodbDoc = new AWS.DynamoDB.DocumentClient();

    API Version 2012-08-10

    38

    Amazon DynamoDB Getting Started Guide

    Step 3.6: Delete an Item (DeleteItem)

    http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DeleteItem.htmlhttp://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DeleteItem.html
  • 7/24/2019 02.Amazon DynamoDB

    43/70

    var table = "Movies";

    var year = 2015;

    var title = "The Big New Movie";

    var params = {

    TableName:table,

    Key:{

    "year":year,

    "title":title

    },

    ConditionExpression:"rating

  • 7/24/2019 02.Amazon DynamoDB

    44/70

    Step 4: Query and Scan the Data (p. 40)

    Step 4: Query and Scan the Data

    DynamoDB pro