赞
踩
AWS DynamoDB及S3操作文档(一)
AmazonDynamoDB client= AmazonDynamoDBClientBuilder.standard().withRegion(Regions.US_WEST_1).build();
DynamoDB dynamoDB = new DynamoDB(client);
//获取需要操作的表
Table table = dynamoDB.getTable(TABLE_NAME);
String tableName = "Movies";
try {
//设置表的分区键和排序键(主键和副键)
Table table = dynamoDB.createTable(tableName,
Arrays.asList(new KeySchemaElement("year", KeyType.HASH), // 设置分区键
new KeySchemaElement("title", KeyType.RANGE)), // 设置排序键
//设置分区键和排序键的数据的属性,N表示数字,S表示字符串
Arrays.asList(new AttributeDefinition("year", ScalarAttributeType.N),
new AttributeDefinition("title", ScalarAttributeType.S)),
//设置预配吞吐量,ProvisionedThroughput 参数是必填项;
new ProvisionedThroughput(10L, 10L));
table.waitForActive();
//输出表的状态和描述
System.out.println("Success. Table status: " +table.getDescription().getTableStatus());
}
//设置新项目的分区键year和排序键title
int year = 2015;
String title = "The Big New Movie";
//申明一个map型对象为infomap,在info属性中存储plot和rating
final Map<String, Object> infoMap = new HashMap<String, Object>();
infoMap.put("plot", "Nothing happens at all.");
infoMap.put("rating", 0);
try {
//将项目添加至表table中,“year”、“title”为分区键和排序键
PutItemOutcome outcome = table.putItem(new Item().withPrimaryKey("year", year,
"title",title).withMap("info", infoMap));
}
//设置删除项目必须满足的条件,“year”、“title”为分区键和排序键
//只有在withConditionExpression中的条件满足时才删除项目
//withValueMap中给withConditionExpression中的条件赋值
DeleteItemSpec deleteItemSpec = new DeleteItemSpec().withPrimaryKey(new PrimaryKey("year", year, "title",title)).withConditionExpression("info.rating <= :val") .withValueMap(new ValueMap().withNumber(":val", 5.0));
try {
table.deleteItem(deleteItemSpec);
}
//设置查询项目满足的条件
//withFilterExpression是项目必须满足的条件
ScanSpec scanSpec = new ScanSpec().withProjectionExpression("#yr, title,info.rating")
.withFilterExpression("#yr between :start_yr and :end_yr")
.withNameMap(newNameMap().with("#yr", "year"))
.withValueMap(new ValueMap().withNumber(":start_yr",1950)
.withNumber(":end_yr", 1959));
try {
//利用迭代器输出查询到的项目
ItemCollection<ScanOutcome> items = table.scan(scanSpec);
Iterator<Item> iter = items.iterator();
while (iter.hasNext()) {
Item item = iter.next();
System.out.println(item.toString());
}
}
//设置分区键和排序键
int year = 2015;
String title = "The Big New Movie";
//设置需要更新的项目必须满足的条件
//withPrimaryKey中设置分区键和排序键
//withUpdateExpression中设置更新的属性
//withValueMap中设置更新的属性的值,其中a为一个列表
//withReturnValues为返回值
//只有在withConditionExpression中条件满足时才会更新项目
UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("year",year, "title", title)
.withUpdateExpression("set info.rating = :r, info.plot=:p, info.actors=:a").withConditionExpression("size(info.actors) > :num").withValueMap(new ValueMap().withNumber(":r", 5.5)
.withString(":p","Everything happens all at once.").withList(":a", Arrays.asList("Larry", "Moe", "Curly"))).withReturnValues(ReturnValue.UPDATED_NEW);
try {
UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
}
以上即为DynamoDB的简单操作
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。