Dynamodb 简明教程
DynamoDB - Load Table
加载表通常包含创建源文件、确保源文件符合与 DynamoDB 兼容的语法、将源文件发送到目的地,然后确认成功填充。
利用 GUI 控制台、Java 或其他选项执行任务。
Load Table using GUI Console
结合使用命令行和控制台加载数据。您可以通过多种方式加载数据,其中一些方式如下 -
-
The Console
-
The Command Line
-
Code and also
-
数据管道(本教程稍后讨论的功能)
However, for speed, this example uses both the shell and console. First, load the source data into the destination with the following syntax −
aws dynamodb batch-write-item -–request-items file://[filename]
例如 -
aws dynamodb batch-write-item -–request-items file://MyProductData.json
Verify the success of the operation by accessing the console at −
从导航窗格选择 Tables ,并从表格列表中选择目标表格。
选择 Items 选项卡以检查用于填充表格的数据。选择 Cancel 以返回到表格列表。
Load Table using Java
首先创建一个源文件以使用 Java。我们的源文件使用 JSON 格式。每个产品有两个主键属性(Id 和命名法)和一个 JSON 映射(Stat)。
[
{
"ID" : ... ,
"Nomenclature" : ... ,
"Stat" : { ... }
},
{
"ID" : ... ,
"Nomenclature" : ... ,
"Stat" : { ... }
},
...
]
您可以查看以下示例 -
{
"ID" : 122,
"Nomenclature" : "Particle Blaster 5000",
"Stat" : {
"Manufacturer" : "XYZ Inc.",
"sales" : "1M+",
"quantity" : 500,
"img_src" : "http://www.xyz.com/manuals/particleblaster5000.jpg",
"description" : "A laser cutter used in plastic manufacturing."
}
}
下一步是将文件放在您的应用程序使用的目录中。
Java 主要使用 putItem 和 path methods 来执行加载。
您可以查看以下代码示例来处理文件并加载它−
import java.io.File;
import java.util.Iterator;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ObjectNode;
public class ProductsLoadData {
public static void main(String[] args) throws Exception {
AmazonDynamoDBClient client = new AmazonDynamoDBClient()
.withEndpoint("http://localhost:8000");
DynamoDB dynamoDB = new DynamoDB(client);
Table table = dynamoDB.getTable("Products");
JsonParser parser = new JsonFactory()
.createParser(new File("productinfo.json"));
JsonNode rootNode = new ObjectMapper().readTree(parser);
Iterator<JsonNode> iter = rootNode.iterator();
ObjectNode currentNode;
while (iter.hasNext()) {
currentNode = (ObjectNode) iter.next();
int ID = currentNode.path("ID").asInt();
String Nomenclature = currentNode.path("Nomenclature").asText();
try {
table.putItem(new Item()
.withPrimaryKey("ID", ID, "Nomenclature", Nomenclature)
.withJSON("Stat", currentNode.path("Stat").toString()));
System.out.println("Successful load: " + ID + " " + Nomenclature);
} catch (Exception e) {
System.err.println("Cannot add product: " + ID + " " + Nomenclature);
System.err.println(e.getMessage());
break;
}
}
parser.close();
}
}