2017-04-06 3 views
0

私はDynamoDBを初めて使用しており、hashKeyとsortKeyを使用してDynamoDBのテーブルでどのようにクエリを実行できるかを知りたがっています。Partition KeyとSort Key [Java]に基づいてDynamoDBを照会する方法は?

私はテーブルItemsを持っています。それは `sのスキーマは、今私がProduct = "apple"ID = 100を持つすべての項目を取得したい、product = 10を持つすべての項目を取得するための

1. Product (Partition Key of type String) 
2. ID (Sort Key of type int) 
3. Date (attribute of type String) 

マイクエリ

Items it = new Items(); 
it.setProduct("apple"); 

DynamoDBQueryExpression<Items> queryExpression = new DynamoDBQueryExpression<Items>() 
      .withHashKeyValues(it); 


List<Items> itemList = mapper.query(Items.class, queryExpression); 

であるしかし。

DynamoDBの場合、Javaにクエリを書くことはできますか?

答えて

2

パーティションキーとソートキーを使用してDynamoDBからデータを取得します。 DynamoDBMapperクラスにあるloadメソッドを使用できます。あなたのケースItemクラスで

DynamoDBMapper mapper = new DynamoDBMapper(dynamoDBClient); 
String product = "ball"; 
Integer id = 1; 
Item itemObj = mapper.load(Items.class, product, id); 

Modelクラス、すなわち: -

あなたはハッシュとレンジのキーのための適切なアノテーションで定義されたアイテムのクラスを持っている必要があります。

@DynamoDBTable(tableName = "Items") 
public class Item { 

    private String product; 
    private Integer id; 

    @DynamoDBHashKey(attributeName = "Product") 
    public String getProduct() { 
     return autoID; 
    } 
    @DynamoDBRangeKey(attributeName = "ID") 
    public String getId() { 
     return id; 
    }   
} 
+0

私は、テーブルを言って、エラーを取得します。 RANGEキー –

+0

IDのマッピングはソートキーではなく範囲キーです。 –

+0

答えをモデルクラスで更新しました。同様に、キー以外の属性も定義できます。しかし、負荷が機能するためには、非キー属性は必要ありません。ソートキーは、それ以外の場合は範囲​​キーと呼ばれます – notionquest

0

私は(マッパーと注釈を使用していない)、より低レベルの方法を追加したいと思います:

String accessKey = ...; // Don't hardcode keys in production. 
String secretKey = ...; 

AmazonDynamoDB dynamoDBClient = 
     = AmazonDynamoDBClientBuilder 
      .standard() 
      .withRegion("us-east-1") 
      .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey))) 
      .build(); 

String tableName = ... 
Map.Entry<String, AttributeValue> partitionKey = ... 
Map.Entry<String, AttributeValue> sortKey = ... 

GetItemRequest request = 
    new GetItemRequest().withTableName(tableName) 
         .withKey(partitionKey, sortKey); 

GetItemResult result = dynamoDBClient.getItem(request); 
Map<String, AttributeValue> item = result.getItem(); 
関連する問題