c# to create table in Dynamo DB

create table in dynamodb using c#
aws dynamodb c# tutorial
dynamodb streams c#
access dynamodb from lambda c#
dynamodb query c#
dynamodb documentation
dynamodb document model
dynamodb table

I am trying to create a table in DynamoDB and post that, list out all the existing tables. The code I used is

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Amazon.Runtime;

namespace DynamoDBTester
{
class Program
{
    private static AmazonDynamoDBClient client = new AmazonDynamoDBClient();
    private static string tableName = "DummyTable";
    static void Main(string[] args)
    {
       // try
        //{
            CreateDummyTable();
           // ListMyTables();

            Console.WriteLine("To continue, press Enter");
            Console.ReadLine();
        //}
        //catch (AmazonDynamoDBException e) { Console.WriteLine(e.Message); }
        //catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
        //catch (Exception e) { Console.WriteLine(e.Message); }
    }

    private static void CreateDummyTable()
    {
        Console.WriteLine("\n*** Creating DummyTable ***");
        var request = new CreateTableRequest
        {
            AttributeDefinitions = new List<AttributeDefinition>()
        {
            new AttributeDefinition
            {
                AttributeName = "Id",
                AttributeType = "N"
            }
            ,
            new AttributeDefinition
            {
                AttributeName = "DateTime",
                AttributeType = "S"
            }
            ,
            new AttributeDefinition
            {
                AttributeName = "Temperature",
                AttributeType = "N"
            }
        },
            KeySchema = new List<KeySchemaElement>
            {
                new KeySchemaElement
            {
                AttributeName = "Id",
                KeyType = "HASH" //Partition key
            },
                new KeySchemaElement
            {
                AttributeName = "DateTime",
                KeyType = "RANGE" //Partition key
            },
                new KeySchemaElement
            {
                AttributeName = "Temperature",
                KeyType = "RANGE" //Partition key
            }

        },
            ProvisionedThroughput = new ProvisionedThroughput
            {
                ReadCapacityUnits = 5,
                WriteCapacityUnits = 6
            },
            TableName = tableName
        };
        var response = client.CreateTable(request);
        var tableDescription = response.TableDescription;
        Console.WriteLine("{1}: {0} \t ReadsPerSec: {2} \t WritesPerSec: {3}",
                  tableDescription.TableStatus,
                  tableDescription.TableName,
                  tableDescription.ProvisionedThroughput.ReadCapacityUnits,
                  tableDescription.ProvisionedThroughput.WriteCapacityUnits);

        string status = tableDescription.TableStatus;
        Console.WriteLine(tableName + " - " + status);

        WaitUntilTableReady(tableName);
    }
    private static void WaitUntilTableReady(string tableName)
    {
        string status = null;
        // Let us wait until table is created. Call DescribeTable.
        do
        {
            System.Threading.Thread.Sleep(5000); // Wait 5 seconds.
            try
            {
                var res = client.DescribeTable(new DescribeTableRequest
                {
                    TableName = tableName
                });

                Console.WriteLine("Table name: {0}, status: {1}",
                          res.Table.TableName,
                          res.Table.TableStatus);
                status = res.Table.TableStatus;
            }
            catch (ResourceNotFoundException)
            {
                // DescribeTable is eventually consistent. So you might
                // get resource not found. So we handle the potential exception.
            }
        } while (status != "ACTIVE");
    }
    private static void ListMyTables()
    {
        Console.WriteLine("\n*** listing tables ***");
        string lastTableNameEvaluated = null;
        do
        {
            var request = new ListTablesRequest
            {
                Limit = 2,
                ExclusiveStartTableName = lastTableNameEvaluated
            };

            var response = client.ListTables(request);
            foreach (string name in response.TableNames)
                Console.WriteLine(name);

            lastTableNameEvaluated = response.LastEvaluatedTableName;
        } while (lastTableNameEvaluated != null);
    }



}
}

But I am getting and error as

Additional information: 1 validation error detected: Value '[com.amazonaws.dynamodb.v20120810.KeySchemaElement@21c24a, com.amazonaws.dynamodb.v20120810.KeySchemaElement@7357d4d9, com.amazonaws.dynamodb.v20120810.KeySchemaElement@7b38ae72]' at 'keySchema' failed to satisfy constraint: Member must have length less than or equal to 2

My table name is DummyTable

It should have 3 columns:

1.Id

2.DateTime

3.Temperature

where Id is the PrimaryKey

Problem:-

1) Only one attribute can be defined as RANGE key. You have two attributes DateTime and Temperature defined as RANGE key

Solution:-

If you need two different RANGE keys, you can use Local Secondary Index (LSI). A table can have 5 LSI.

LSI

Example: Create, Update, Delete, and List Tables Using the AWS , To create a table using the AWS SDK for .NET low-level API. Create an instance of the AmazonDynamoDBClient class. Create an instance of the CreateTableRequest class to provide the request information. You must provide the table name, primary key, and the provisioned throughput values. Execute the AmazonDynamoDBClient. The following C# code example creates tables and uploads data to the tables. The resulting table structure and data is shown in Creating Tables and Loading Sample Data. For step-by-step instructions to run this code in Visual Studio, see .NET Code Examples.

  1. While creating the Table you only need to specify the Primary key of that table (KeySchema) either

a.simple primary key (only partition key) or

b.complex primary key(partition +sort key)

In your case its complex primary key and you only need to mention partition key and sort key (only schema required for dynamo db )

No need to mention the additional attribute (additional column name while creating the table) .

Code change needed is to remove the addition attribute definition and schema

var request = new CreateTableRequest
        {
            AttributeDefinitions = new List<AttributeDefinition>()
        {
            new AttributeDefinition
            {
                AttributeName = "Id",
                AttributeType = "N"
            }
            ,
            new AttributeDefinition
            {
                AttributeName = "DateTime",
                AttributeType = "S"
            }
}

KeySchema = new List<KeySchemaElement>
            {
                new KeySchemaElement
            {
                AttributeName = "Id",
                KeyType = "HASH" //Partition key
            },
                new KeySchemaElement
            {
                AttributeName = "DateTime",
                KeyType = "RANGE" //Range key
            }
}

Working with DynamoDB Tables in .NET, the AWS SDK for .NET API with Amazon DynamoDB. The following C# code example creates tables and uploads data to the tables. The resulting table  In the Create DynamoDB table screen, do the following: In the Table name box, enter Thread . For the Primary key, do the following:

While creating table , you have to keep only columns which will have hash or range schemaattribute.

for additional columns you dont need to mention while creating the table. while inserting an item you can dynamically append any number of columns to the record and it will be saved against the specified hash/range attribute.

Creating Example Tables and Uploading Data Using the AWS SDK , In this blog we will be looking at creating a DynamoDB client, then using that client to create a Duration: 23:30 Posted: Feb 19, 2018 Deleting a Table. Create a Node.js module with the file name ddb_deletetable.js. Be sure to configure the SDK as previously shown. To access DynamoDB, create an AWS.DynamoDB service object. Create a JSON object containing the parameters needed to delete a table, which in this example includes the name of the table provided as a command-line parameter.

DynamoDB, I will show you how to create a Table and perform CRUD operations on it. Amazon DynamoDB provides a low-level API and an Object  Amazon DynamoDB is a key-value and document database that delivers single-digit millisecond performance at any scale. It’s a fully managed, multi-region, multi-master, durable database with built-in security, backup and restore, and in-memory caching for internet-scale applications. DynamoDB tables. DynamoDB stores data in tables.

Step-by-Step Guide to Amazon DynamoDB for .NET Developers, The following C# example creates a Table object that represents the ProductCatalog table in Amazon DynamoDB. Example. Table table = Table.​LoadTable(client,  C# code example showing how to create, update, and delete a table using the AWS SDK for .NET. Example: Create, Update, Delete, and List Tables Using the AWS SDK for .NET Low-Level API - Amazon DynamoDB

Working with Items in DynamoDB Using the AWS SDK for .NET , You must provide the primary key of the item that you want to retrieve as shown in the following C# code example. Example. Table table = Table.LoadTable(client,  Step 1: Create a DynamoDB Client. The first step in the Microsoft .NET and DynamoDB Tutorial is to create a client that gives you access to the Amazon DynamoDB API. The Main function in DynamoDB_intro does this by calling a createClient function implemented in the 01_CreateClient.cs file.

Comments
  • It says that key schema can not have more than 2 items. At max you can have one partition key and one sortkey as part of key schema.
  • I tried removing the Temperature attribute from the KeySchema. Then I'm getting an error as Additional information: One or more parameter values were invalid: Number of attributes in KeySchema does not exactly match number of attributes defined in AttributeDefinitions