C# для создания таблицы в БД Динамо
Я пытаюсь создать таблицу в DynamoDB и опубликовать ее, перечислить все существующие таблицы. Код, который я использовал
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);
}
}
}
Но я получаю и ошибку как
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
Мое имя таблицы DummyTable
Он должен иметь 3 столбца:
1.Id
2.DateTime
3.Temperature
где Id
это PrimaryKey
2 ответа
При создании таблицы вы должны хранить только столбцы, которые будут иметь хэш или атрибут схемы диапазона.
для дополнительных столбцов вам не нужно упоминать при создании таблицы. при вставке элемента вы можете динамически добавлять любое количество столбцов к записи, и он будет сохранен в указанном атрибуте hash/range.
- При создании таблицы вам нужно только указать первичный ключ этой таблицы (KeySchema)
a.simple первичный ключ (только ключ раздела) или
Первичный ключ b.complex (раздел + ключ сортировки)
В вашем случае это сложный первичный ключ, и вам нужно только упомянуть ключ раздела и ключ сортировки (для динамо-базы данных требуется только схема)
Не нужно упоминать дополнительный атрибут (имя дополнительного столбца при создании таблицы) .
Для изменения кода необходимо удалить определение атрибута и схему
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
}
}
Проблема:-
1) Только один атрибут может быть определен как ключ RANGE. У вас есть два атрибута DateTime
а также Temperature
определяется как ключ RANGE
Решение:-
Если вам нужны два разных ключа RANGE, вы можете использовать Local Secondary Index (LSI). Стол может иметь 5 LSI.