【问题标题】:DynamoDb HashKey Attribute nameDynamoDb HashKey 属性名称
【发布时间】:2023-03-04 13:40:01
【问题描述】:

有没有办法在java中获取dynamodb表的HashKey的属性名?

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

【问题讨论】:

    标签: java amazon-dynamodb


    【解决方案1】:

    您只需要在描述表格时迭代keySchemasattributeDefinitions

    DynamodbTable描述有如下结构,(我用clojure-aws,你可以用aws cli看表结构)

    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"}}
    

    您可以在其中看到需要迭代的 key-schemaattribute-definitions 键。

    1) 请参阅TableDescription#getKeySchema 的文档以获取HASHRANGE 密钥。

    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) 对于其他字段,您需要在 List<AttributeDefinitions> 上进行迭代,您在 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());
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多