Reader small image

You're reading from  DynamoDB Cookbook

Product typeBook
Published inSep 2015
Publisher
ISBN-139781784393755
Edition1st Edition
Concepts
Right arrow
Author (1)
Tanmay Deshpande
Tanmay Deshpande
author image
Tanmay Deshpande

Tanmay Deshpande is a Hadoop and big data evangelist. He currently works with Schlumberger as a Big Data Architect in Pune, India. He has interest in a wide range of technologies, such as Hadoop, Hive, Pig, NoSQL databases, Mahout, Sqoop, Java, cloud computing, and so on. He has vast experience in application development in various domains, such as oil and gas, finance, telecom, manufacturing, security, and retail. He enjoys solving machine-learning problems and spends his time reading anything that he can get his hands on. He has great interest in open source technologies and has been promoting them through his talks. Before Schlumberger, he worked with Symantec, Lumiata, and Infosys. Through his innovative thinking and dynamic leadership, he has successfully completed various projects. He regularly blogs on his website http://hadooptutorials.co.in. You can connect with him on LinkedIn at https://www.linkedin.com/in/deshpandetanmay/. He has also authored Mastering DynamoDB, published in August 2014, DynamoDB Cookbook, published in September 2015, Hadoop Real World Solutions Cookbook-Second Edition, published in March 2016, Hadoop: Data Processing and Modelling, published in August, 2016, and Hadoop Blueprints, published in September 2016, all by Packt Publishing.
Read more about Tanmay Deshpande

Right arrow

Chapter 2. Operating with DynamoDB Tables

In this chapter, we will cover the following topics:

  • Creating a table using the AWS SDK for Java

  • Creating a table using the AWS SDK for .Net

  • Creating a table using the AWS SDK for PHP

  • Updating a table using the AWS SDK for Java

  • Updating a table using the AWS SDK for .Net

  • Updating a table using the AWS SDK for PHP

  • Listing tables using the AWS SDK for Java

  • Listing tables using the AWS SDK for .Net

  • Listing tables using the AWS SDK for PHP

  • Deleting a table using the AWS SDK for Java

  • Deleting a table using the AWS SDK for .Net

  • Deleting a table using the AWS SDK for PHP

Introduction


In the previous chapter, we discussed how to perform various DynamoDB operations using the console. In this chapter, we will focus on how to use the SDK provided by Amazon to perform operations. Amazon has provided SDKs in various programming languages, out of which we are going to see operations in Java, .Net, and PHP. So, get ready to get your hands dirty with the code!

Creating a table using the AWS SDK for Java


Let's start with creating a table in DynamoDB using SDKs provided by Amazon.

Getting ready

To program various DynamoDB table operations, you can use the IDE of your choice, for example, Eclipse, NetBeans, Visual Studio, and so on. Here, we will be using the Eclipse IDE. In the previous chapter, we have already seen how to download and set up the Eclipse IDE.

How to do it…

Let's first see how to create a table in DynamoDB using the AWS SDK for Java.

You can create a Maven project and add the AWS SDK Maven dependency. The latest version available can be found at http://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk/.

Here, I will be using Version 1.9.30, and its POM looks like this:

<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-java-sdk</artifactId>
  <version>1.9.30</version>
</dependency>

Here are the steps to create a table using the AWS SDK for Java:

  1. Create an instance of the DynamoDB...

Creating a table using the AWS SDK for .Net


Now, let's understand how to create a DynamoDB table using the AWS SDK for .Net.

Getting ready

You can use an IDE, such as Visual Studio to code these recipes. You can refer to the AWS documentation on how to set up your workstation at http://aws.amazon.com/sdk-for-net/.

How to do it…

Let's start with creating a table called productTableNet:

  1. Instantiate the CreateTable request specifying AttributeDefinition and KeySchema. We will create the table having both the HASH and RANGE Keys. We will set the provisioned read and write capacity units to be one:

    AmazonDynamoDBClient client = new AmazonDynamoDBClient();
    string tableName = "productTableNet";
    var request=new CreateTableRequest{
      AttributeDefinitions=newList<AttributeDefinition>(){
        newAttributeDefinition{
          AttributeName="id", AttributeType="N"
        },
        newAttributeDefinition{
          AttributeName="type", AttributeType="S"
        }
      },
      KeySchema=newList<KeySchemaElement>{
        newKeySchemaElement...

Creating a table using the AWS SDK for PHP


Now, let's understand how to create a DynamoDB table using the AWS SDK for PHP.

Getting ready…

You can use the IDE of your choice to code these recipes.

How to do it…

Let's start with creating a table called productTablePHP:

  1. Instantiate the DynamoDB client for PHP. Specify the AWS region in which you wish to create the table in:

    $client = DynamoDbClient::factory(array(
        'profile' => 'default',
        'region' => 'us-west-1'  
    ));
  2. Invoke the createTable method by specifying the details, such as the table name, hash and range keys, and provisioned capacity units. Here, we will create a table with the primary key as the composite hash and range keys:

    $result = $client->createTable(array(
        'TableName' => $tableName,
        'AttributeDefinitions' => array(
            array(
                'AttributeName' => 'id',
                'AttributeType' => 'N'
            ),
            array(
                'AttributeName' => 'type',
                'AttributeType' ...

Updating a table using the AWS SDK for Java


Now, let's understand how to update a DynamoDB table using the AWS SDK for Java.

Getting ready…

You can use the IDE of your choice to code these recipes.

How to do it…

In this recipe, we will learn how to update the already created DynamoDB table. Here, we will update the read and write capacity units:

  1. Create an instance of the Table class and initiate it by calling the getTable method:

    AmazonDynamoDBClient client = new AmazonDynamoDBClient(new ProfileCredentialsProvider());
    client.setRegion(Region.getRegion(Regions.US_EAST_1));
    DynamoDB dynamoDB = new DynamoDB(client);
    Table table = dynamoDB.getTable("productTableJava");
  2. Now, create an instance of the provisioned throughput, and set the read and write capacity units. Earlier, we set the read and write capacity units to one, and now we will update it to two:

    ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput().withReadCapacityUnits(2L).withWriteCapacityUnits(2L);
  3. Now, invoke the updateTable...

Updating a table using the AWS SDK for .Net


Now, let's understand how to update a DynamoDB table using the AWS SDK for .Net.

Getting ready

You can use the IDE of your choice to code these recipes.

How to do it…

In this recipe, we will learn how to update the provisioned capacity of the already created table using the AWS SDK for .Net:

  1. Create an update table request and provide the new read and write capacity units:

    AmazonDynamoDBClient client = new AmazonDynamoDBClient();
    string tableName = "productTableNet";
    var request=new UpdateTableRequest(){
      TableName=tableName,
      ProvisionedThroughput = new ProvisionedThroughput(){
        ReadCapacityUnits=2,
          WriteCapacityUnits=2
      }
    };
  2. Invoke the updateTable method from the DynamoDB client to update the table with the provided capacity units:

    var response = client.UpdateTable(request);
  3. It takes some time for DynamoDB to make the changes effective. So, it's always a best practice to wait until the table becomes active again. By default, the AWS SDK for...

Updating a table using the AWS SDK for PHP


Now, let's understand how to update a DynamoDB table using the AWS SDK for PHP.

Getting ready

You can use the IDE of your choice to code these recipes.

How to do it…

In this recipe, we will learn how to update the read and write capacity units for an already created table:

  1. Create an instance of the DynamoDB client and invoke the updateTable method, providing the details of the new provisioned throughout capacity units. Here, we will update the read and write capacity units to two:

    $tableName = 'productTablePHP';
    $result = $client->updateTable(array(
        'TableName' => $tableName,
        'ProvisionedThroughput'    => array(
            'ReadCapacityUnits'    => 2,        
            'WriteCapacityUnits' => 2          
        )
    ));
  2. DynamoDB takes some time to make the changes effective. So, it's a best practice to wait until the table gets effective again:

    $client->waitUntilTableExists(array('TableName' => $tableName));

How it works…

Once we invoke...

Listing tables using the AWS SDK for Java


Now, let's understand how to list all the DynamoDB tables using the AWS SDK for Java.

Getting ready

You can use the IDE of your choice to code these recipes.

How to do it…

In this recipe, we will learn how to list the tables that we created earlier using the AWS SDK for Java:

  1. Create an instance of the DynamoDB class and instantiate it with the AWS credential provider:

    DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
        new ProfileCredentialsProvider()));
  2. Invoke the listTables method of the DynamoDB class to get a list of all the tables:

    TableCollection<ListTablesResult> tables = dynamoDB.listTables();
    Iterator<Table> iterator = tables.iterator();
  3. Now, you can iterate over the list to get the details of the tables you have created:

    while (iterator.hasNext()) {
      Table table = iterator.next();
      System.out.println(table.getTableName());
    }

How it works…

The list table API internally calls DynamoDB services to fetch the details of the tables...

Listing tables using the AWS SDK for .Net


Now, let's understand how to list all the DynamoDB tables using the AWS SDK for .Net.

Getting ready

You can use the IDE of your choice to code these recipes.

How to do it…

In this recipe, we will learn how to list the tables that we created earlier using the AWS SDK for .Net:

  1. Create an instance of the DynamoDB client and invoke the listTables method to get all the tables that you created earlier:

    AmazonDynamoDBClient client = new AmazonDynamoDBClient();
    var response = client.ListTables();
    ListTablesResult result = response.ListTablesResult;
  2. Iterate over the results variable to get the names of all the tables:

    foreach (string name in result.TableNames)
    Console.WriteLine(name);
  3. The AWS SDK for .Net also supports pagination for the list table request. If you want the list of tables to arrive in a paginated manner, then you may think of exploring it.

How it works…

The List table API internally calls DynamoDB services to fetch the details of the tables you have...

Listing tables using the AWS SDK for PHP


Now, let's understand how to list all the DynamoDB tables using the AWS SDK for PHP.

Getting ready

You can use the IDE of your choice to code these recipes.

How to do it…

In this recipe, we will learn how to list the tables we created earlier using the AWS SDK for PHP:

  1. Create an instance of the DynamoDB client and invoke the listTables method:

    $client = DynamoDbClient::factory(array(
        'profile' => 'default',
        'region' => 'us-west-2'  
    ));
    $response = $client->listTables();
  2. Iterate over the list to get the details of the tables:

    foreach ($response['TableNames'] as $key => $value) {
           echo "$value" . PHP_EOL;
     }
  3. The AWS SDK for PHP also provides the option to limit the number of tables that are retrieved, and it supports pagination as well. If you have a lot of tables created, then you can fetch the results in the paginated format, as follows:

    $tablesArray = array();
    do {
      $response = $client->listTables(array(
        'Limit' => 5,...

Deleting a table using the AWS SDK for Java


Now, let's understand how to delete a DynamoDB table using the AWS SDK for Java.

Getting ready

You can use the IDE of your choice to code these recipes.

How to do it…

In this recipe, we will learn how to delete the table that we created earlier using the AWS SDK for Java:

  1. Initialize the DynamoDB Client and call the getTable method by providing the name of the table that you wish to delete:

    AmazonDynamoDBClient client = new AmazonDynamoDBClient(new ProfileCredentialsProvider());
    client.setRegion(Region.getRegion(Regions.US_EAST_1));
    DynamoDB dynamoDB = new DynamoDB(client);
    Table table = dynamoDB.getTable("productTableJava");
  2. Now, call the delete method of the table class to delete the table:

    table.delete();
  3. Like create and update, delete also takes some time. So, it's good practice to wait until delete takes place on DynamoDB:

    table.waitForDelete();

How it works…

Once we invoke these APIs, the AWS SDK deletes the table forever. So, I request that you use this...

Deleting a table using the AWS SDK for .Net


Now, let's understand how to delete a DynamoDB table using the AWS SDK for .Net.

Getting ready

You can use the IDE of your choice to code these recipes.

How to do it…

In this recipe, we will learn how to delete the table that we created earlier using the AWS SDK for .Net:

  1. Create a delete table request specifying the name of the table to be deleted:

    string tableName = "productTableNet";
    var request = new DeleteTableRequest
                {
                    TableName = tableName
                };
  2. Invoke the DeleteTable method to delete the table:

       var response = client.DeleteTable(request);
  3. Like create and update, delete also takes some time before the changes are effective.

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed...

Deleting a table using the AWS SDK for PHP


Now, let's understand how to delete a DynamoDB table using the AWS SDK for PHP.

Getting ready

You can use the IDE of your choice to code these recipes.

How to do it…

In this recipe, we will learn how to delete the table that we created earlier using the AWS SDK for PHP:

  1. Create the DynamoDB Client and invoke the deleteTable method, specifying the name of the table to be deleted:

    $tableName = 'productTablePHP';
    $client = DynamoDbClient::factory(array(
        'profile' => 'default',
        'region' => 'us-west-2'  
    ));
    $result = $client->deleteTable(array(
        'TableName' => $tableName
    ));
  2. As soon as you invoke this API, DynamoDB puts it into the DELETING status, and after a while, it has been completely deleted. It's good practice to wait until the table is deleted:

    $client->waitUntilTableNotExists(array('TableName' => $tableName));

How it works…

Once we invoke these APIs, the AWS SDK deletes the table forever. So, I request that you use this API...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
DynamoDB Cookbook
Published in: Sep 2015Publisher: ISBN-13: 9781784393755
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Tanmay Deshpande

Tanmay Deshpande is a Hadoop and big data evangelist. He currently works with Schlumberger as a Big Data Architect in Pune, India. He has interest in a wide range of technologies, such as Hadoop, Hive, Pig, NoSQL databases, Mahout, Sqoop, Java, cloud computing, and so on. He has vast experience in application development in various domains, such as oil and gas, finance, telecom, manufacturing, security, and retail. He enjoys solving machine-learning problems and spends his time reading anything that he can get his hands on. He has great interest in open source technologies and has been promoting them through his talks. Before Schlumberger, he worked with Symantec, Lumiata, and Infosys. Through his innovative thinking and dynamic leadership, he has successfully completed various projects. He regularly blogs on his website http://hadooptutorials.co.in. You can connect with him on LinkedIn at https://www.linkedin.com/in/deshpandetanmay/. He has also authored Mastering DynamoDB, published in August 2014, DynamoDB Cookbook, published in September 2015, Hadoop Real World Solutions Cookbook-Second Edition, published in March 2016, Hadoop: Data Processing and Modelling, published in August, 2016, and Hadoop Blueprints, published in September 2016, all by Packt Publishing.
Read more about Tanmay Deshpande