I am getting an error for creating a dynamo DB table using AWS SDK for Java 2.0. The hash key is specified but still getting error
@Bean
ApplicationRunner applicationRunner(DynamoDbClient dynamoDbClient) {
return args -> {
dynamoDbClient.listTables().tableNames().forEach(System.out::println);
CreateTableRequest createTableRequest =
CreateTableRequest.builder()
.keySchema(
KeySchemaElement.builder().keyType(KeyType.HASH).attributeName("id").build())
.attributeDefinitions(
AttributeDefinition.builder()
.attributeName("campaign_name")
.attributeType(ScalarAttributeType.S)
.build())
.provisionedThroughput(
ProvisionedThroughput.builder()
.readCapacityUnits(5L)
.writeCapacityUnits(5L)
.build())
.tableName("campaign")
.build();
try {
dynamoDbClient.createTable(createTableRequest);
dynamoDbClient.listTables().tableNames().forEach(System.out::println);
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
}
};
}
Error:
Hash Key not specified in Attribute Definitions. Type unknown. (Service: DynamoDb, Status Code: 400, Request ID: bed4b8c3-f312-4a9d-8d7b-a2184dacce54)
I am trying to create a table with key and non key column
@Bean
ApplicationRunner applicationRunner(DynamoDbClient dynamoDbClient) {
return args -> {
dynamoDbClient.listTables().tableNames().forEach(System.out::println);
CreateTableRequest createTableRequest =
CreateTableRequest.builder()
.attributeDefinitions(
AttributeDefinition.builder()
.attributeName("id")
.attributeType(ScalarAttributeType.S)
.build(),
AttributeDefinition.builder()
.attributeName("name")
.attributeType(ScalarAttributeType.S)
.build())
.keySchema(
KeySchemaElement.builder()
.keyType(KeyType.HASH)
.attributeName("campaign_id")
.build())
.provisionedThroughput(
ProvisionedThroughput.builder()
.readCapacityUnits(5L)
.writeCapacityUnits(5L)
.build())
.tableName("campaign")
.build();
try {
dynamoDbClient.createTable(createTableRequest);
dynamoDbClient.listTables().tableNames().forEach(System.out::println);
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
}
};
}
Error - The number of attributes in key schema must match the number of attributesdefined in attribute definitions.
I believe you need to add a AttributeDefinition
for your KeySchemeElement
as well.
Try adding the following to your attributeDefinitions
call
AttributeDefinition.builder()
.attributeName("campaign_id")
.attributeType(ScalarAttributeType.S)
.build()