Количество атрибутов в схеме ключей должно соответствовать количеству атрибутов, определенных в определениях атрибутов
Я пытаюсь создать простую таблицу с использованием оболочки javascript DynamoDB, и я получаю это исключение:
{
"message": "The number of attributes in key schema must match the number of attributes defined in attribute definitions.",
"code": "ValidationException",
"time": "2015-06-16T10:24:23.319Z",
"statusCode": 400,
"retryable": false
}
Ниже приведена таблица Im, пытающаяся создать:
var params = {
TableName: 'table_name',
KeySchema: [
{
AttributeName: 'hash_key_attribute_name',
KeyType: 'HASH',
},
],
AttributeDefinitions: [
{
AttributeName: 'hash_key_attribute_name',
AttributeType: 'S',
},
{
AttributeName: 'attribute_name_1',
AttributeType: 'S',
}
],
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 1,
},
};
dynamodb.createTable(params, function(err, data) {
if (err) print(err);
else print(data);
});
Однако, если я добавлю второй атрибут в keySchema, он отлично работает. Ниже рабочего стола:
var params = {
TableName: 'table_name',
KeySchema: [
{
AttributeName: 'hash_key_attribute_name',
KeyType: 'HASH',
},
{
AttributeName: 'attribute_name_1',
KeyType: 'RANGE',
}
],
AttributeDefinitions: [
{
AttributeName: 'hash_key_attribute_name',
AttributeType: 'S',
},
{
AttributeName: 'attribute_name_1',
AttributeType: 'S',
}
],
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 1,
},
};
dynamodb.createTable(params, function(err, data) {
if (err) print(err);
else print(data);
});
Я не хочу добавлять диапазон к ключевой схеме. Любая идея, как это исправить?
Ответы
Ответ 1
DynamoDB является схематичным (кроме схемы ключей)
То есть вам нужно указать схему ключа (имя и тип атрибута) при создании таблицы. Ну, вам не нужно указывать какие-либо неключевые атрибуты. Вы можете поместить элемент с любым атрибутом позже (обязательно должны включать ключи, конечно).
На странице документации, AttributeDefinitions
определяется как:
Массив атрибутов, описывающих схему ключей для таблицы и индексов.
При создании таблицы поле AttributeDefinitions
используется только для хэшей и/или диапазонов диапазона. В вашем первом случае есть только хэш-ключ (номер 1), в то время как вы предоставляете 2 атрибута. Это основная причина исключения.
TL; DR Не включайте определения нечетких атрибутов в AttributeDefinitions
.
Ответ 2
Когда вы используете неключевой атрибут в разделе "AttributeDefinitions", вы должны использовать его в качестве индекса, иначе он будет работать против работы dynamodb. см. ссылка
Таким образом, не нужно помещать неключевой атрибут в "AttributeDefinitions", если вы не собираетесь использовать его в качестве индекса или первичного ключа.
var params = {
TableName: 'table_name',
KeySchema: [ // The type of of schema. Must start with a HASH type, with an optional second RANGE.
{ // Required HASH type attribute
AttributeName: 'UserId',
KeyType: 'HASH',
},
{ // Optional RANGE key type for HASH + RANGE tables
AttributeName: 'RemindTime',
KeyType: 'RANGE',
}
],
AttributeDefinitions: [ // The names and types of all primary and index key attributes only
{
AttributeName: 'UserId',
AttributeType: 'S', // (S | N | B) for string, number, binary
},
{
AttributeName: 'RemindTime',
AttributeType: 'S', // (S | N | B) for string, number, binary
},
{
AttributeName: 'AlarmId',
AttributeType: 'S', // (S | N | B) for string, number, binary
},
// ... more attributes ...
],
ProvisionedThroughput: { // required provisioned throughput for the table
ReadCapacityUnits: 1,
WriteCapacityUnits: 1,
},
LocalSecondaryIndexes: [ // optional (list of LocalSecondaryIndex)
{
IndexName: 'index_UserId_AlarmId',
KeySchema: [
{ // Required HASH type attribute - must match the table HASH key attribute name
AttributeName: 'UserId',
KeyType: 'HASH',
},
{ // alternate RANGE key attribute for the secondary index
AttributeName: 'AlarmId',
KeyType: 'RANGE',
}
],
Projection: { // required
ProjectionType: 'ALL', // (ALL | KEYS_ONLY | INCLUDE)
},
},
// ... more local secondary indexes ...
],
};
dynamodb.createTable(params, function(err, data) {
if (err) ppJson(err); // an error occurred
else ppJson(data); // successful response
});
Ответ 3
У меня также была эта проблема, и я опубликую здесь, что пошло не так для меня, если это помогает кому-то другому.
В моем CreateTableRequest у меня был пустой массив для GlobalSecondaryIndexes.
CreateTableRequest createTableRequest = new CreateTableRequest
{
TableName = TableName,
ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = 2, WriteCapacityUnits = 2 },
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement
{
AttributeName = "Field1",
KeyType = KeyType.HASH
},
new KeySchemaElement
{
AttributeName = "Field2",
KeyType = KeyType.RANGE
}
},
AttributeDefinitions = new List<AttributeDefinition>()
{
new AttributeDefinition
{
AttributeName = "Field1",
AttributeType = ScalarAttributeType.S
},
new AttributeDefinition
{
AttributeName = "Field2",
AttributeType = ScalarAttributeType.S
}
},
//GlobalSecondaryIndexes = new List<GlobalSecondaryIndex>
//{
//}
};
Комментируя эти строки в создании таблицы, я решил свою проблему. Поэтому я думаю, что список должен быть пустым, а не пустым.