Reputation: 447
Is there any way to get the attribute name of HashKey of a dynamodb table in java?
e.g., if the dyanmodb table schema is
(
"HashKey, String", SSNId
"SortKey, Long", Pincode
"String", Name
)
So I should be able to get the output like this:-
getHashKeyAttributeName(String tableName) --> SSNId
getSortkeyAttributeName(String tableName) --> Pincode
getOtherAttributeList(String tableName) --> Name
Upvotes: 1
Views: 1718
Reputation: 31222
you simply need to iterate on the keySchemas
and attributeDefinitions
when you the describe the table.
DynamodbTable
description has following structure, (I'm using clojure-aws, you can use aws cli to see the table structure)
user=> (db/describe-table {:profile "aws-profile" :endpoint "us-west-2"} "KeyValueLookupTable1")
{:table {:key-schema [{:key-type "HASH", :attribute-name "leaseKey"}], :table-size-bytes 201, :attribute-definitions [{:attribute-name "leaseKey", :attribute-type "S"}], :creation-date-time #object[org.joda.time.DateTime 0x4c6ece3 "2017-06-07T15:50:35.057-07:00"], :item-count 1, :table-status "ACTIVE", :table-name "KeyValueLookupTable1", :provisioned-throughput {:read-capacity-units 10, :write-capacity-units 10, :number-of-decreases-today 0}, :table-arn "arn:aws:dynamodb:us-west-2:033814027302:table/KeyValueLookupTable1"}}
where you can see key-schema
and attribute-definitions
keys which you will need to iterate on.
1) See the documentation for TableDescription#getKeySchema
to get the HASH
and RANGE
keys.
example with java8
DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient())
String getHashKeyAttributeName(String tableName) {
TableDescription tableSchema = dynamoDB.getTable(tableName).describe();
return tableSchema.getKeySchema().stream()
.filter(x -> x.getKeyType().equals(KeyType.HASH.toString()))
.findFirst().get().getAttributeName();
}
String getSortkeyAttributeName(String tableName) {
TableDescription tableSchema = dynamoDB.getTable(tableName).describe();
return tableSchema.getKeySchema().stream()
.filter(x -> x.getKeyType().equals(KeyType.RANGE.toString()))
.findFirst().get().getAttributeName();
}
2) For other fields, you need to iterate on List<AttributeDefinitions>
which you get on tableDescription.getAttributeDefinitions
List<String> getOtherAttributeList(String tableName) {
DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient());
TableDescription tableSchema = dynamoDB.getTable(tableName).describe();
return tableSchema.getAttributeDefinitions().stream()
.map(AttributeDefinition::getAttributeName)
.collect(Collectors.toList());
}
Upvotes: 2