如何基于分区键和排序键查询DynamoDB [Java]?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43257068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to query DynamoDB based on Partition Key and Sort Key [Java]?
提问by John Constantine
I am new to DynamoDB and wanted to know how can we query on a table in DynamoDB with the hashKey and sortKey.
我是 DynamoDB 的新手,想知道我们如何使用 hashKey 和 sortKey 查询 DynamoDB 中的表。
I have a table named Items
. It`s schema is
我有一张名为Items
. 它的架构是
1. Product (Partition Key of type String)
2. ID (Sort Key of type int)
3. Date ( attribute of type String)
My query for getting all items having product = 10
is
我获取所有项目的查询product = 10
是
Items it = new Items();
it.setProduct("apple");
DynamoDBQueryExpression<Items> queryExpression = new DynamoDBQueryExpression<Items>()
.withHashKeyValues(it);
List<Items> itemList = mapper.query(Items.class, queryExpression);
But, now I want to get all items having Product = "apple"
and ID = 100
.
但是,现在我想获得所有具有Product = "apple"
和 的项目ID = 100
。
I can I write a query in Java
for DynamoDB
.
我可以在Java
for 中写一个查询DynamoDB
。
回答by notionquest
In order to get the data from DynamoDB using partition key and sort key. You can use the load
method present on DynamoDBMapper
class.
为了使用分区键和排序键从 DynamoDB 获取数据。您可以使用课堂load
上的方法DynamoDBMapper
。
DynamoDBMapper mapper = new DynamoDBMapper(dynamoDBClient);
String product = "ball";
Integer id = 1;
Item itemObj = mapper.load(Items.class, product, id);
Model class i.e. in your case Item class:-
模型类,即在您的情况下 Item 类:-
You should have the Item class defined with proper annotation for Hash and Range key.
您应该使用 Hash 和 Range 键的正确注释定义 Item 类。
@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;
}
}
回答by MarcG
I would like to add a more low-level way (not using Mapper and annotations):
我想添加一个更底层的方式(不使用 Mapper 和注释):
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();
回答by smac2020
Given this DynamoDB table:
鉴于此 DynamoDB 表:
The table has the following details:
该表具有以下详细信息:
- Partition key — Artist
- Sort key — SongTitle
- 分区键 — 艺术家
- 排序键 — SongTitle
Given this class:
鉴于这个类:
@DynamoDBTable(tableName="Music")
public class MusicItems {
//Set up Data Members that correspond to items in the Music Table
private String artist;
private String songTitle;
private String albumTitle;
private int awards;
@DynamoDBHashKey(attributeName="Artist")
public String getArtist() { return this.artist; }
public void setArtist(String artist) {this.artist = artist; }
@DynamoDBRangeKey(attributeName="SongTitle")
public String getSongTitle() { return this.songTitle; }
public void setSongTitle(String title) {this.songTitle = title; }
@DynamoDBAttribute(attributeName="AlbumTitle")
public String getAlbumTitle() { return this.albumTitle; }
public void setAlbumTitle(String title) {this.albumTitle = title; }
@DynamoDBAttribute(attributeName="Awards")
public int getAwards() { return this.awards; }
public void setAwards(int awards) {this.awards = awards; }
}
This code works:
此代码有效:
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
public class UseDynamoMapping {
public static void main(String[] args)
{
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
MusicItems items = new MusicItems();
try{
//add new content to the Music Table
items.setArtist("Famous Band");
items.setSongTitle("Our Famous Song");
items.setAlbumTitle("Our First Album");
items.setAwards(0);
// Save the item
DynamoDBMapper mapper = new DynamoDBMapper(client);
mapper.save(items);
//Load an item based on the Partition Key and Sort Key
//both values need to be passed to the mapper.load method
String artist = "Famous Band";
String songQueryTitle = "Our Famous Song";
// Retrieve the item.
MusicItems itemRetrieved = mapper.load(MusicItems.class, artist, songQueryTitle);
System.out.println("Item retrieved:");
System.out.println(itemRetrieved);
//Modify the Award value
itemRetrieved.setAwards(2);
mapper.save(itemRetrieved);
System.out.println("Item updated:");
System.out.println(itemRetrieved);
System.out.print("Done");
}
catch (Exception e)
{
e.getStackTrace();
}
}
}
回答by Vikky
GetItemRequest getItemRequest = new GetItemRequest().withTableName("Employee").
addKeyEntry("departmentId", new AttributeValue().withS(String.valueOf(departmentId))).
addKeyEntry("employeeId", new AttributeValue().withN(String.valueOf(employeeId)));
Map<String, AttributeValue> responseItem = dynamoDbClient.getItem(getItemRequest).getItem();