開始使用增強型文件 API - AWS SDK for Java 2.x

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

開始使用增強型文件 API

增強型文件 API 需要與 DynamoDB 增強型用戶端 API 所需的相同相依性。它還需要DynamoDbEnhancedClient執行個體,如本主題開頭所示。

由於增強型文件 API 的發行版本為 2.20.3 AWS SDK for Java 2.x,因此您需要該版本或更高版本。

建立 DocumentTableSchemaDynamoDbTable

若要使用增強型文件 API 針對 DynamoDB 資料表叫用命令,請將資料表與用戶端 DynamoDbTable<EnhancedDocument> 資源物件建立關聯。

增強型用戶端的 table()方法會建立DynamoDbTable<EnhancedDocument>執行個體,並需要 DynamoDB 資料表名稱和 的參數DocumentTableSchema

DocumentTableSchema 的建置器需要主要索引鍵和一或多個屬性轉換器提供者。AttributeConverterProvider.defaultProvider() 方法提供預設類型的轉換器。即使您提供自訂屬性轉換器提供者,也應該指定它。您可以將選用的次要索引鍵新增至建置器。

下列程式碼片段顯示程式碼,該程式碼會產生存放無結構描述EnhancedDocument物件的 DynamoDB person資料表的用戶端表示法。

DynamoDbTable<EnhancedDocument> documentDynamoDbTable = enhancedClient.table("person", TableSchema.documentSchemaBuilder() // Specify the primary key attributes. .addIndexPartitionKey(TableMetadata.primaryIndexName(),"id", AttributeValueType.S) .addIndexSortKey(TableMetadata.primaryIndexName(), "lastName", AttributeValueType.S) // Specify attribute converter providers. Minimally add the default one. .attributeConverterProviders(AttributeConverterProvider.defaultProvider()) .build()); // Call documentTable.createTable() if "person" does not exist in DynamoDB. // createTable() should be called only one time.

以下顯示本節中所用person物件的 JSON 表示法。

{ "id": 1, "firstName": "Richard", "lastName": "Roe", "age": 25, "addresses": { "home": { "zipCode": "00000", "city": "Any Town", "state": "FL", "street": "123 Any Street" }, "work": { "zipCode": "00001", "city": "Anywhere", "state": "FL", "street": "100 Main Street" } }, "hobbies": [ "Hobby 1", "Hobby 2" ], "phoneNumbers": [ { "type": "Home", "number": "555-0100" }, { "type": "Work", "number": "555-0119" } ] }