dynamoDB数据库

薛利
2023-12-01
  • 首先安装AWSCLI
  • 安装后;在cmd输入 aws --version 检验是否安装成功
  • 然后;在cmd输入:aws configure设置aws的密钥
  • 最后使用一下代码进行数据库的CRUD操作
  • 如果能帮助大家请手动点赞
package com.skysoft.modules.controller;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.*;
import com.amazonaws.services.dynamodbv2.document.spec.*;
import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.model.*;
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;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 创建表Movies
 * Created by hyq on 2017/5/16.
 */
public class MoviesCreateTable {

    public static void main(String[] args) {
        //加载驱动
        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
        //建立连接
        DynamoDB dynamoDB = new DynamoDB(client);
        //表名
        String tableName = "Movies";
        try {
            System.out.println("Attempting to create table; please wait...");
            //创建表
            Table table = dynamoDB.createTable(tableName,
                    Arrays.asList(new KeySchemaElement("year", KeyType.HASH), // KeySchemaElement 用于主键的属性
                            new KeySchemaElement("title", KeyType.RANGE)), // Sort key
                    Arrays.asList(new AttributeDefinition("year", ScalarAttributeType.N),
                            new AttributeDefinition("title", ScalarAttributeType.S)),//键架构属性的数据类型。
                    new ProvisionedThroughput(10L, 10L));
            table.waitForActive();
            System.out.println("Success.  Table status: " + table.getDescription().getTableStatus());

        } catch (Exception e) {
            System.err.println("Unable to create table: ");
            System.err.println(e.getMessage());
        }
    }

    /**
     * 数据加载
     */
    @Test
    public void MoviesLoadData() throws IOException {
        //加载驱动
        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
        //建立连接
        DynamoDB dynamoDB = new DynamoDB(client);
        //获取Movies表
        Table table = dynamoDB.getTable("Movies");
        //获取json文件
        JsonParser parser = new JsonFactory().createParser(new File("E:\\IdeaWorkSpace\\dynamodbdemo\\src\\main\\resources\\test.json"));


        JsonNode rootNode = new ObjectMapper().readTree(parser);
        Iterator<JsonNode> iter = rootNode.iterator();

        ObjectNode currentNode;
        //遍历json对象实现循环添加
        while (iter.hasNext()) {
            currentNode = (ObjectNode) iter.next();

            int year = currentNode.path("year").asInt();
            String title = currentNode.path("title").asText();

            try {
                table.putItem(new Item().withPrimaryKey("year", year, "title", title).withJSON("info",
                        currentNode.path("info").toString()));
                System.out.println("PutItem succeeded: " + year + " " + title);

            } catch (Exception e) {
                System.err.println("Unable to add movie: " + year + " " + title);
                System.err.println(e.getMessage());
                break;
            }
        }
        System.out.println("test  success");
        parser.close();
    }

    /**
     * 添加操作
     * 创建一个新的项目
     * 您将新项目添加到Movies表中
     */
    @Test
    public void MoviesCreateItem() {
        //加载驱动
        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
        //建立连接
        DynamoDB dynamoDB = new DynamoDB(client);
        //获取Movies表
        Table table = dynamoDB.getTable("Movies");
        //参数
        int year = 2015;
        String title = "The Big New Movie";
        //info信息
        final Map<String, Object> infoMap = new HashMap<String, Object>();
        infoMap.put("plot", "Nothing happens at all.");
        infoMap.put("rating", 0);
        //添加
        try {
            System.out.println("Adding a new item...");
            PutItemOutcome outcome = table
                    .putItem(new Item().withPrimaryKey("year", year, "title", title).withMap("info", infoMap));

            System.out.println("PutItem succeeded:\n" + outcome.getPutItemResult());

        } catch (Exception e) {
            System.err.println("Unable to add item: " + year + " " + title);
            System.err.println(e.getMessage());
        }
    }

    /**
     * getItem方法从Movies表中读取该项
     */
    @Test
    public void MoviesGetItem() {
        //加载驱动
        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
        //建立连接
        DynamoDB dynamoDB = new DynamoDB(client);
        //获取Movies表
        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        GetItemSpec spec = new GetItemSpec().withPrimaryKey("year", year, "title", title);

        try {
            System.out.println("Attempting to read the item...");
            Item outcome = table.getItem(spec);
            System.out.println("GetItem succeeded: " + outcome);

        } catch (Exception e) {
            System.err.println("Unable to read item: " + year + " " + title);
            System.err.println(e.getMessage());
        }
    }

    /**
     * 您可以使用该updateItem方法修改现有项目。
     * 可以更新现有属性的值,添加新属性或删除属性
     */
    @Test
    public void MoviesUpdateItem() {
        //加载驱动
        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
        //建立连接
        DynamoDB dynamoDB = new DynamoDB(client);
        //获取Movies表
        Table table = dynamoDB.getTable("Movies");
        int year = 2015;
        String title = "The Big New Movie";

        UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("year", year, "title", title)
                .withUpdateExpression("set info.rating = :r, info.plot=:p, info.actors=:a")
                .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 {
            System.out.println("Updating the item...");
            UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
            System.out.println("UpdateItem succeeded:\n" + outcome.getItem().toJSONPretty());

        } catch (Exception e) {
            System.err.println("Unable to update item: " + year + " " + title);
            System.err.println(e.getMessage());
        }
    }

    /**
     * 原子计数器:
     * 您可以使用该updateItem方法来
     * 增加或减少现有属性的值,
     * 而不会影响其他写入请求
     */
    @Test
    public void MoviesContentItem() {
        //加载驱动
        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
        //建立连接
        DynamoDB dynamoDB = new DynamoDB(client);
        //获取Movies表
        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("year", year, "title", title)
                .withUpdateExpression("set info.rating = info.rating + :val")//每次+1
                .withValueMap(new ValueMap().withNumber(":val", 1)).withReturnValues(ReturnValue.UPDATED_NEW);

        try {
            System.out.println("Incrementing an atomic counter...");
            UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
            System.out.println("UpdateItem succeeded:\n" + outcome.getItem().toJSONPretty());

        } catch (Exception e) {
            System.err.println("Unable to update item: " + year + " " + title);
            System.err.println(e.getMessage());
        }

    }

    /**
     * 以下程序显示如何使用UpdateItem条件。
     * 如果条件求值为true,则更新成功; 否则,不执行更新。
     */
    @Test
    public void updateItem() {
        //加载驱动
        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
        //建立连接
        DynamoDB dynamoDB = new DynamoDB(client);
        //获取Movies表
        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        UpdateItemSpec updateItemSpec = new UpdateItemSpec()
                .withPrimaryKey(new PrimaryKey("year", year, "title", title)).withUpdateExpression("remove info.actors[0]")
                .withConditionExpression("size(info.actors) > :num").withValueMap(new ValueMap().withNumber(":num", 1))
                .withReturnValues(ReturnValue.UPDATED_NEW);

        // Conditional update (we expect this to fail)
        try {
            System.out.println("Attempting a conditional update...");
            UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
            System.out.println("UpdateItem succeeded:\n" + outcome.getItem().toJSONPretty());

        } catch (Exception e) {
            System.err.println("Unable to update item: " + year + " " + title);
            System.err.println(e.getMessage());
        }
    }

    /**
     * 您可以使用该deleteItem方法通过指定其主键来删除一个项目。
     * 如果不满足条件,您可以选择提供一个ConditionExpression以防止项目删除。
     */
    @Test
    public void deleteItem() {
        //加载驱动
        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
        //建立连接
        DynamoDB dynamoDB = new DynamoDB(client);
        //获取Movies表
        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        DeleteItemSpec deleteItemSpec = new DeleteItemSpec()
                .withPrimaryKey(new PrimaryKey("year", year, "title", title)).withConditionExpression("info.rating <= :val")
                .withValueMap(new ValueMap().withNumber(":val", 8.0));

        // Conditional delete (we expect this to fail)

        try {
            System.out.println("Attempting a conditional delete...");
            table.deleteItem(deleteItemSpec);
            System.out.println("DeleteItem succeeded");
        } catch (Exception e) {
            System.err.println("Unable to delete item: " + year + " " + title);
            System.err.println(e.getMessage());
        }
    }

    /**
     * 查询
     */
    @Test
    public void MoviesQuery() {
        //加载驱动
        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
        //建立连接
        DynamoDB dynamoDB = new DynamoDB(client);
        //获取Movies表
        Table table = dynamoDB.getTable("Movies");

        HashMap<String, String> nameMap = new HashMap<String, String>();
        nameMap.put("#yr", "year");

        HashMap<String, Object> valueMap = new HashMap<String, Object>();
        valueMap.put(":yyyy", 2013);
        QuerySpec querySpec = new QuerySpec().withKeyConditionExpression("#yr = :yyyy")
                .withNameMap(nameMap).withValueMap(valueMap);
        ItemCollection<QueryOutcome> items = null;
        Iterator<Item> iterator = null;
        Item item = null;

        try {
            System.out.println("Movies from 2013");
            items = table.query(querySpec);

            iterator = items.iterator();
            while (iterator.hasNext()) {
                item = iterator.next();
                System.out.println(item.getNumber("year") + ": " + item.getString("title"));
            }

        } catch (Exception e) {
            System.err.println("Unable to query movies from 2013");
            System.err.println(e.getMessage());
        }

//        valueMap.put(":yyyy", 1992);
//        valueMap.put(":letter1", "A");
//        valueMap.put(":letter2", "L");
//
//        querySpec.withProjectionExpression("#yr, title, info.genres, info.actors[0]")
//                .withKeyConditionExpression("#yr = :yyyy and title between :letter1 and :letter2").withNameMap(nameMap)
//                .withValueMap(valueMap);
//
//        try {
//            System.out.println("Movies from 1992 - titles A-L, with genres and lead actor");
//            items = table.query(querySpec);
//
//            iterator = items.iterator();
//            while (iterator.hasNext()) {
//                item = iterator.next();
//                System.out.println(item.getNumber("year") + ": " + item.getString("title") + " " + item.getMap("info"));
//            }
//
//        } catch (Exception e) {
//            System.err.println("Unable to query movies from 1992:");
//            System.err.println(e.getMessage());
//        }


    }

    /**
     * 扫描
     * ProjectionExpression 指定扫描结果中所需的属性。
     * FilterExpression 指定只返回满足条件的项的条件。所有其他项目都被丢弃。
     */
    @Test
    public void MoviesScan() {
        //加载驱动
        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
        //建立连接
        DynamoDB dynamoDB = new DynamoDB(client);
        //获取Movies表
        Table table = dynamoDB.getTable("Movies");

        ScanSpec scanSpec = new ScanSpec().withProjectionExpression("#yr, title, info.rating")
                .withFilterExpression("#yr between :start_yr and :end_yr").withNameMap(new NameMap().with("#yr", "year"))
                .withValueMap(new ValueMap().withNumber(":start_yr", 2011).withNumber(":end_yr", 2015));

        try {
            ItemCollection<ScanOutcome> items = table.scan(scanSpec);

            Iterator<Item> iter = items.iterator();
            while (iter.hasNext()) {
                Item item = iter.next();
                System.out.println(item.toString());
            }

        } catch (Exception e) {
            System.err.println("Unable to scan the table:");
            System.err.println(e.getMessage());
        }
    }

    /**
     * 删表  跑路
     */
    public void deleteTeble(){
        //加载驱动
        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
        //建立连接
        DynamoDB dynamoDB = new DynamoDB(client);
        //获取Movies表
        Table table = dynamoDB.getTable("Movies");

        try {
            System.out.println("Attempting to delete table; please wait...");
            table.delete();
            table.waitForDelete();
            System.out.print("Success.");

        }
        catch (Exception e) {
            System.err.println("Unable to delete table: ");
            System.err.println(e.getMessage());
        }
    }
}
 类似资料: