Example usage for com.amazonaws.services.dynamodbv2.model AttributeValue AttributeValue

List of usage examples for com.amazonaws.services.dynamodbv2.model AttributeValue AttributeValue

Introduction

In this page you can find the example usage for com.amazonaws.services.dynamodbv2.model AttributeValue AttributeValue.

Prototype

public AttributeValue() 

Source Link

Document

Default constructor for AttributeValue object.

Usage

From source file:AmazonDynamoDBSample_PutThrottled.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();/*  w  w w.  j  av a  2  s  . com*/

    try {
        String tableName = "my-favorite-movies-table";

        // Create a table with a primary hash key named 'name', which holds
        // a string
        CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                .withKeySchema(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition().withAttributeName("name")
                        .withAttributeType(ScalarAttributeType.S))
                .withProvisionedThroughput(
                        new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));

        // Create table if it does not exist yet
        TableUtils.createTableIfNotExists(dynamoDB, createTableRequest);
        // wait for the table to move into ACTIVE state
        TableUtils.waitUntilActive(dynamoDB, tableName);

        // Describe our new table
        DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
        TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
        System.out.println("Table Description: " + tableDescription);

        // Add an item
        Map<String, AttributeValue> item = newItem("Bill & Ted's Excellent Adventure", 1989, "****", "James",
                "Sara");
        PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);

        // Add another item
        item = newItem("Airplane", 1980, "*****", "James", "Billy Bob");
        putItemRequest = new PutItemRequest(tableName, item);
        putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);

        Thread[] thrds = new Thread[16];
        for (int i = 0; i < thrds.length; i++) {
            thrds[i] = newItemCreationThread(tableName, i);
            thrds[i].start();
        }
        for (Thread thrd : thrds) {
            thrd.join();
        }

        // Scan items for movies with a year attribute greater than 1985
        HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
        Condition condition = new Condition().withComparisonOperator(ComparisonOperator.GT.toString())
                .withAttributeValueList(new AttributeValue().withN("1985"));
        scanFilter.put("year", condition);
        ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
        ScanResult scanResult = dynamoDB.scan(scanRequest);
        System.out.println("Result: " + scanResult);

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:NYSEScan.java

License:Open Source License

private static void scan(String tableName) {
    Table table = null;//from   w  w w  .j  a  va2s.  co m
    try {
        // Create table if it does not exist yet
        if (!Tables.doesTableExist(dynamoDB, tableName)) {
            System.out.println("Table " + tableName + " is does not exist");
        } else {
            table = dynamo.getTable(tableName);
        }
        // select * from stock_eod where stockTicker = 'HCA' and v > 1000000;
        // http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html
        Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>();
        expressionAttributeValues.put(":val", new AttributeValue().withN("1000000"));

        //Below is not recommended as stockTicker is part of the key
        expressionAttributeValues.put(":st", new AttributeValue().withS("HCA"));

        ScanRequest scanRequest = new ScanRequest().withTableName(tableName)
                .withFilterExpression("v > :val and stockTicker = :st")
                // select stockTicker, tradeDate, v from stock_eod where stockTicker = 'HCA' and v > 1000000;
                .withProjectionExpression("stockTicker,tradeDate,v")
                .withExpressionAttributeValues(expressionAttributeValues);

        ScanResult result = dynamoDB.scan(scanRequest);

        for (Map<String, AttributeValue> item : result.getItems()) {
            System.out.println(item);
        }

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:KinesisMessageModelDynamoDBTransformer.java

License:Open Source License

/**
 * Helper method to map nonempty String attributes to an AttributeValue.
 *
 * @param item The map of attribute names to AttributeValues to store the attribute in
 * @param key The key to store in the map
 * @param value The value to check before inserting into the item map
 *//* w ww.  j  av a2 s. co  m*/
private void putStringIfNonempty(Map<String, AttributeValue> item, String key, String value) {
    if (!value.equals(null) && !value.isEmpty()) {
        item.put(key, new AttributeValue().withS(value));
    }
}

From source file:DynamoDB.java

License:Open Source License

private static Map<String, AttributeValue> newItem(String Id, String message) {
    Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
    //item.put("Id", new AttributeValue().withS(message));
    item.put("Id", new AttributeValue().withS(Id));
    item.put("message", new AttributeValue().withS(message));
    return item;/* w w  w  .  j  a v a 2  s  .  com*/
}

From source file:AmazonDynamoDBSample.java

License:Open Source License

private static Map<String, AttributeValue> newItem(int id, String name, String desc, ByteBuffer image,
        Timestamp storyTime, Timestamp currentTime, double lati, double longi) {
    Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
    item.put("storyID", new AttributeValue().withN(Integer.toString(id)));
    item.put("name", new AttributeValue(name));
    item.put("desc", new AttributeValue(desc));
    //        ByteBuffer b =  createBody();
    item.put("image", new AttributeValue().withB(image));
    item.put("storyTime", new AttributeValue().withS(String.valueOf(storyTime)));
    item.put("currentTime", new AttributeValue().withS(String.valueOf(currentTime)));
    item.put("lati", new AttributeValue().withN(Double.toString(lati)));
    item.put("longi", new AttributeValue().withN(Double.toString(longi)));

    return item;/*  w  w w. java 2s  .c o  m*/
}

From source file:RandomQuery1OnDynamoDB.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();//  w  w w.  j a v a2 s. c  om

    try {

        // Describe our new table
        DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
        TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
        System.out.println("Table Description: " + tableDescription);

        System.out.println("Table count :" + tableDescription.getItemCount());

        long lStartTime = new Date().getTime();
        System.out.println("start time: " + lStartTime);
        Random rn = new Random();
        // Scan items for movies with a year attribute greater than 1985
        Long lItem = tableDescription.getItemCount();
        int iNoOfItems = lItem.intValue();
        System.out.println("no of item " + lItem);
        for (int i = 0; i <= 49999; i++) {
            String randomInt = Integer.toString(rn.nextInt(iNoOfItems));
            HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
            Condition condition = new Condition().withComparisonOperator(ComparisonOperator.EQ.toString())
                    .withAttributeValueList(new AttributeValue().withN(randomInt));
            scanFilter.put("id", condition);
            ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
            ScanResult scanResult = dynamoDB.scan(scanRequest);
            System.out.println("Random No :" + randomInt + ":: Query no: " + (i + 1));

        }
        // calculate time difference for update file time
        long lEndTime = new Date().getTime();
        long difference = lEndTime - lStartTime;
        System.out.println("Elapsed milliseconds: " + difference);
        System.out.println("Elapsed seconds: " + difference * 0.001);
        System.out.println("Elapsed Minutes: " + (int) ((difference / (1000 * 60)) % 60));

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:RandomQuery2OnDynamoDB.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();//ww w  .  j av  a  2 s  .  co  m

    try {

        // Describe our new table
        DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
        TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
        System.out.println("Table Description: " + tableDescription);
        long lStartTime = new Date().getTime();
        System.out.println("start time: " + lStartTime);
        Random rn = new Random();
        Long lItem = tableDescription.getItemCount();
        int iNoOfItems = lItem.intValue();
        int iPointOnePercent = (int) ((int) iNoOfItems * 0.001);
        int iOnePercent = (int) ((int) iNoOfItems * 0.01);
        System.out.println("TotalItems:" + iNoOfItems + "::0.1% of data is :: " + iPointOnePercent
                + "::1% of data is :" + iOnePercent);

        // Generating 25000 random queries for 0.1 to 1 % of the data
        for (int i = 0; i <= 24999; i++) {
            String randomInt = Integer.toString(rn.nextInt(iOnePercent - iPointOnePercent) + iPointOnePercent);
            HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
            Condition condition = new Condition().withComparisonOperator(ComparisonOperator.EQ.toString())
                    .withAttributeValueList(new AttributeValue().withN(randomInt));
            scanFilter.put("id", condition);
            ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
            ScanResult scanResult = dynamoDB.scan(scanRequest);
            System.out.println("Random No :" + randomInt + ":: Query no: " + (i + 1));

        }
        // calculate time difference for update file time
        long lEndTime = new Date().getTime();
        long difference = lEndTime - lStartTime;
        System.out.println("Elapsed milliseconds: " + difference);
        System.out.println("Elapsed seconds: " + difference * 0.001);
        System.out.println("Elapsed Minutes: " + (int) ((difference / (1000 * 60)) % 60));

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:amazon.dynamodb.config.DynamoDBManager.java

License:Open Source License

/**
 * Query Amazon DynamoDB//ww  w  . j  a va 2 s .co m
 *
 * @param hashKey Hash key for the query request.
 *
 * @param range The range of geohashs to query.
 *
 * @return The query result.
 */
public List<QueryResult> queryGeohash(QueryRequest queryRequest, long hashKey, GeoHashRango range) {
    List<QueryResult> queryResults = new ArrayList<QueryResult>();
    Map<String, AttributeValue> lastEvaluatedKey = null;

    do {
        Map<String, Condition> keyConditions = new HashMap<String, Condition>();

        Condition hashKeyCondition = new Condition().withComparisonOperator(ComparisonOperator.EQ)
                .withAttributeValueList(new AttributeValue().withN(String.valueOf(hashKey)));
        keyConditions.put(config.getHashKeyAttributeName(), hashKeyCondition);

        AttributeValue minRange = new AttributeValue().withN(Long.toString(range.getRangeMin()));
        AttributeValue maxRange = new AttributeValue().withN(Long.toString(range.getRangeMax()));

        Condition geohashCondition = new Condition().withComparisonOperator(ComparisonOperator.BETWEEN)
                .withAttributeValueList(minRange, maxRange);
        keyConditions.put(config.getGeohashAttributeName(), geohashCondition);

        queryRequest.withTableName(config.getTableName()).withKeyConditions(keyConditions)
                .withIndexName(config.getGeohashIndexName()).withConsistentRead(true)
                .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL)
                .withExclusiveStartKey(lastEvaluatedKey);

        QueryResult queryResult = config.getDynamoDBClient().query(queryRequest);
        queryResults.add(queryResult);

        lastEvaluatedKey = queryResult.getLastEvaluatedKey();

    } while (lastEvaluatedKey != null);

    return queryResults;
}

From source file:amazon.dynamodb.config.DynamoDBManager.java

License:Open Source License

public GetPointResult getPoint(GetPointRequest getPointRequest) {
    long geohash = S2Manager.generateGeohash(getPointRequest.getGeoPoint());
    long hashKey = S2Manager.generateHashKey(geohash, config.getHashKeyLength());

    GetItemRequest getItemRequest = getPointRequest.getGetItemRequest();
    getItemRequest.setTableName(config.getTableName());

    AttributeValue hashKeyValue = new AttributeValue().withN(String.valueOf(hashKey));
    getItemRequest.getKey().put(config.getHashKeyAttributeName(), hashKeyValue);
    getItemRequest.getKey().put(config.getRangeKeyAttributeName(), getPointRequest.getRangeKeyValue());

    GetItemResult getItemResult = config.getDynamoDBClient().getItem(getItemRequest);
    GetPointResult getPointResult = new GetPointResult(getItemResult);

    return getPointResult;
}

From source file:amazon.dynamodb.config.DynamoDBManager.java

License:Open Source License

public PutPointResult putPoint(PutPointRequest putPointRequest) {
    long geohash = S2Manager.generateGeohash(putPointRequest.getGeoPoint());
    long hashKey = S2Manager.generateHashKey(geohash, config.getHashKeyLength());
    String geoJson = GeoJsonMapper.stringFromGeoObject(putPointRequest.getGeoPoint());

    PutItemRequest putItemRequest = putPointRequest.getPutItemRequest();
    putItemRequest.setTableName(config.getTableName());

    AttributeValue hashKeyValue = new AttributeValue().withN(String.valueOf(hashKey));
    putItemRequest.getItem().put(config.getHashKeyAttributeName(), hashKeyValue);
    putItemRequest.getItem().put(config.getRangeKeyAttributeName(), putPointRequest.getRangeKeyValue());
    AttributeValue geohashValue = new AttributeValue().withN(Long.toString(geohash));
    putItemRequest.getItem().put(config.getGeohashAttributeName(), geohashValue);
    AttributeValue geoJsonValue = new AttributeValue().withS(geoJson);
    putItemRequest.getItem().put(config.getGeoJsonAttributeName(), geoJsonValue);

    PutItemResult putItemResult = config.getDynamoDBClient().putItem(putItemRequest);
    PutPointResult putPointResult = new PutPointResult(putItemResult);

    return putPointResult;
}