Search in sources :

Example 1 with Index

use of com.amazonaws.services.dynamodbv2.document.Index in project openhab1-addons by openhab.

the class DynamoDBPersistenceService method createTable.

/**
     * Create table (if not present) and wait for table to become active.
     *
     * Synchronized in order to ensure that at most single thread is creating the table at a time
     *
     * @param mapper
     * @param dtoClass
     * @return whether table creation succeeded.
     */
private synchronized boolean createTable(DynamoDBMapper mapper, Class<?> dtoClass) {
    if (db == null) {
        return false;
    }
    String tableName;
    try {
        ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput(dbConfig.getReadCapacityUnits(), dbConfig.getWriteCapacityUnits());
        CreateTableRequest request = mapper.generateCreateTableRequest(dtoClass);
        request.setProvisionedThroughput(provisionedThroughput);
        if (request.getGlobalSecondaryIndexes() != null) {
            for (GlobalSecondaryIndex index : request.getGlobalSecondaryIndexes()) {
                index.setProvisionedThroughput(provisionedThroughput);
            }
        }
        tableName = request.getTableName();
        try {
            db.getDynamoClient().describeTable(tableName);
        } catch (ResourceNotFoundException e) {
            // No table present, continue with creation
            db.getDynamoClient().createTable(request);
        } catch (AmazonClientException e) {
            logger.error("Table creation failed due to error in describeTable operation", e);
            return false;
        }
        // table found or just created, wait
        return waitForTableToBecomeActive(tableName);
    } catch (AmazonClientException e) {
        logger.error("Exception when creating table", e);
        return false;
    }
}
Also used : AmazonClientException(com.amazonaws.AmazonClientException) ProvisionedThroughput(com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput) ResourceNotFoundException(com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException) CreateTableRequest(com.amazonaws.services.dynamodbv2.model.CreateTableRequest) GlobalSecondaryIndex(com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndex)

Example 2 with Index

use of com.amazonaws.services.dynamodbv2.document.Index in project aws-doc-sdk-examples by awsdocs.

the class DocumentAPILocalSecondaryIndexExample method createTable.

public static void createTable() {
    CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName).withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits((long) 1).withWriteCapacityUnits((long) 1));
    // Attribute definitions for table partition and sort keys
    ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<AttributeDefinition>();
    attributeDefinitions.add(new AttributeDefinition().withAttributeName("CustomerId").withAttributeType("S"));
    attributeDefinitions.add(new AttributeDefinition().withAttributeName("OrderId").withAttributeType("N"));
    // Attribute definition for index primary key attributes
    attributeDefinitions.add(new AttributeDefinition().withAttributeName("OrderCreationDate").withAttributeType("N"));
    attributeDefinitions.add(new AttributeDefinition().withAttributeName("IsOpen").withAttributeType("N"));
    createTableRequest.setAttributeDefinitions(attributeDefinitions);
    // Key schema for table
    ArrayList<KeySchemaElement> tableKeySchema = new ArrayList<KeySchemaElement>();
    // Partition
    tableKeySchema.add(new KeySchemaElement().withAttributeName("CustomerId").withKeyType(KeyType.HASH));
    // key
    // Sort
    tableKeySchema.add(new KeySchemaElement().withAttributeName("OrderId").withKeyType(KeyType.RANGE));
    // key
    createTableRequest.setKeySchema(tableKeySchema);
    ArrayList<LocalSecondaryIndex> localSecondaryIndexes = new ArrayList<LocalSecondaryIndex>();
    // OrderCreationDateIndex
    LocalSecondaryIndex orderCreationDateIndex = new LocalSecondaryIndex().withIndexName("OrderCreationDateIndex");
    // Key schema for OrderCreationDateIndex
    ArrayList<KeySchemaElement> indexKeySchema = new ArrayList<KeySchemaElement>();
    // Partition
    indexKeySchema.add(new KeySchemaElement().withAttributeName("CustomerId").withKeyType(KeyType.HASH));
    // key
    // Sort
    indexKeySchema.add(new KeySchemaElement().withAttributeName("OrderCreationDate").withKeyType(KeyType.RANGE));
    // key
    orderCreationDateIndex.setKeySchema(indexKeySchema);
    // Projection (with list of projected attributes) for
    // OrderCreationDateIndex
    Projection projection = new Projection().withProjectionType(ProjectionType.INCLUDE);
    ArrayList<String> nonKeyAttributes = new ArrayList<String>();
    nonKeyAttributes.add("ProductCategory");
    nonKeyAttributes.add("ProductName");
    projection.setNonKeyAttributes(nonKeyAttributes);
    orderCreationDateIndex.setProjection(projection);
    localSecondaryIndexes.add(orderCreationDateIndex);
    // IsOpenIndex
    LocalSecondaryIndex isOpenIndex = new LocalSecondaryIndex().withIndexName("IsOpenIndex");
    // Key schema for IsOpenIndex
    indexKeySchema = new ArrayList<KeySchemaElement>();
    // Partition
    indexKeySchema.add(new KeySchemaElement().withAttributeName("CustomerId").withKeyType(KeyType.HASH));
    // key
    // Sort
    indexKeySchema.add(new KeySchemaElement().withAttributeName("IsOpen").withKeyType(KeyType.RANGE));
    // key
    // Projection (all attributes) for IsOpenIndex
    projection = new Projection().withProjectionType(ProjectionType.ALL);
    isOpenIndex.setKeySchema(indexKeySchema);
    isOpenIndex.setProjection(projection);
    localSecondaryIndexes.add(isOpenIndex);
    // Add index definitions to CreateTable request
    createTableRequest.setLocalSecondaryIndexes(localSecondaryIndexes);
    System.out.println("Creating table " + tableName + "...");
    System.out.println(dynamoDB.createTable(createTableRequest));
    // Wait for table to become active
    System.out.println("Waiting for " + tableName + " to become ACTIVE...");
    try {
        Table table = dynamoDB.getTable(tableName);
        table.waitForActive();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
Also used : LocalSecondaryIndex(com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndex) Table(com.amazonaws.services.dynamodbv2.document.Table) ArrayList(java.util.ArrayList) AttributeDefinition(com.amazonaws.services.dynamodbv2.model.AttributeDefinition) Projection(com.amazonaws.services.dynamodbv2.model.Projection) ProvisionedThroughput(com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput) CreateTableRequest(com.amazonaws.services.dynamodbv2.model.CreateTableRequest) KeySchemaElement(com.amazonaws.services.dynamodbv2.model.KeySchemaElement)

Example 3 with Index

use of com.amazonaws.services.dynamodbv2.document.Index in project aws-doc-sdk-examples by awsdocs.

the class CreateTablesLoadData method loadSampleThreads.

private static void loadSampleThreads(String tableName) {
    try {
        // 7
        long time1 = (new Date()).getTime() - (7 * 24 * 60 * 60 * 1000);
        // days
        // ago
        // 14
        long time2 = (new Date()).getTime() - (14 * 24 * 60 * 60 * 1000);
        // days
        // ago
        // 21
        long time3 = (new Date()).getTime() - (21 * 24 * 60 * 60 * 1000);
        // days
        // ago
        Date date1 = new Date();
        date1.setTime(time1);
        Date date2 = new Date();
        date2.setTime(time2);
        Date date3 = new Date();
        date3.setTime(time3);
        dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        Table table = dynamoDB.getTable(tableName);
        System.out.println("Adding data to " + tableName);
        Item item = new Item().withPrimaryKey("ForumName", "Amazon DynamoDB").withString("Subject", "DynamoDB Thread 1").withString("Message", "DynamoDB thread 1 message").withString("LastPostedBy", "User A").withString("LastPostedDateTime", dateFormatter.format(date2)).withNumber("Views", 0).withNumber("Replies", 0).withNumber("Answered", 0).withStringSet("Tags", new HashSet<String>(Arrays.asList("index", "primarykey", "table")));
        table.putItem(item);
        item = new Item().withPrimaryKey("ForumName", "Amazon DynamoDB").withString("Subject", "DynamoDB Thread 2").withString("Message", "DynamoDB thread 2 message").withString("LastPostedBy", "User A").withString("LastPostedDateTime", dateFormatter.format(date3)).withNumber("Views", 0).withNumber("Replies", 0).withNumber("Answered", 0).withStringSet("Tags", new HashSet<String>(Arrays.asList("index", "partitionkey", "sortkey")));
        table.putItem(item);
        item = new Item().withPrimaryKey("ForumName", "Amazon S3").withString("Subject", "S3 Thread 1").withString("Message", "S3 Thread 3 message").withString("LastPostedBy", "User A").withString("LastPostedDateTime", dateFormatter.format(date1)).withNumber("Views", 0).withNumber("Replies", 0).withNumber("Answered", 0).withStringSet("Tags", new HashSet<String>(Arrays.asList("largeobjects", "multipart upload")));
        table.putItem(item);
    } catch (Exception e) {
        System.err.println("Failed to create item in " + tableName);
        System.err.println(e.getMessage());
    }
}
Also used : Item(com.amazonaws.services.dynamodbv2.document.Item) Table(com.amazonaws.services.dynamodbv2.document.Table) Date(java.util.Date) HashSet(java.util.HashSet)

Example 4 with Index

use of com.amazonaws.services.dynamodbv2.document.Index in project aws-doc-sdk-examples by awsdocs.

the class LowLevelGlobalSecondaryIndexExample method queryIndex.

public static void queryIndex(String indexName) {
    System.out.println("\n***********************************************************\n");
    System.out.print("Querying index " + indexName + "...");
    QueryRequest queryRequest = new QueryRequest().withTableName(tableName).withIndexName(indexName).withScanIndexForward(true);
    HashMap<String, Condition> keyConditions = new HashMap<String, Condition>();
    if (indexName == "CreateDateIndex") {
        System.out.println("Issues filed on 2013-11-01");
        keyConditions.put("CreateDate", new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(new AttributeValue().withS("2013-11-01")));
        keyConditions.put("IssueId", new Condition().withComparisonOperator(ComparisonOperator.BEGINS_WITH).withAttributeValueList(new AttributeValue().withS("A-")));
    } else if (indexName == "TitleIndex") {
        System.out.println("Compilation errors");
        keyConditions.put("Title", new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(new AttributeValue().withS("Compilation error")));
        keyConditions.put("IssueId", new Condition().withComparisonOperator(ComparisonOperator.BEGINS_WITH).withAttributeValueList(new AttributeValue().withS("A-")));
        // Select
        queryRequest.setSelect(Select.ALL_PROJECTED_ATTRIBUTES);
    } else if (indexName == "DueDateIndex") {
        System.out.println("Items that are due on 2013-11-30");
        keyConditions.put("DueDate", new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(new AttributeValue().withS("2013-11-30")));
        // Select
        queryRequest.setSelect(Select.ALL_PROJECTED_ATTRIBUTES);
    } else {
        System.out.println("\nNo valid index name provided");
        return;
    }
    queryRequest.setKeyConditions(keyConditions);
    QueryResult result = client.query(queryRequest);
    List<Map<String, AttributeValue>> items = result.getItems();
    Iterator<Map<String, AttributeValue>> itemsIter = items.iterator();
    System.out.println();
    while (itemsIter.hasNext()) {
        Map<String, AttributeValue> currentItem = itemsIter.next();
        Iterator<String> currentItemIter = currentItem.keySet().iterator();
        while (currentItemIter.hasNext()) {
            String attr = (String) currentItemIter.next();
            if (attr == "Priority") {
                System.out.println(attr + "---> " + currentItem.get(attr).getN());
            } else {
                System.out.println(attr + "---> " + currentItem.get(attr).getS());
            }
        }
        System.out.println();
    }
}
Also used : Condition(com.amazonaws.services.dynamodbv2.model.Condition) AttributeValue(com.amazonaws.services.dynamodbv2.model.AttributeValue) QueryResult(com.amazonaws.services.dynamodbv2.model.QueryResult) QueryRequest(com.amazonaws.services.dynamodbv2.model.QueryRequest) HashMap(java.util.HashMap) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with Index

use of com.amazonaws.services.dynamodbv2.document.Index in project aws-doc-sdk-examples by awsdocs.

the class LowLevelLocalSecondaryIndexExample method query.

public static void query(String indexName) {
    System.out.println("\n***********************************************************\n");
    System.out.println("Querying table " + tableName + "...");
    QueryRequest queryRequest = new QueryRequest().withTableName(tableName).withConsistentRead(true).withScanIndexForward(true).withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL);
    HashMap<String, Condition> keyConditions = new HashMap<String, Condition>();
    keyConditions.put("CustomerId", new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(new AttributeValue().withS("bob@example.com")));
    if (indexName == "IsOpenIndex") {
        System.out.println("\nUsing index: '" + indexName + "': Bob's orders that are open.");
        System.out.println("Only a user-specified list of attributes are returned\n");
        queryRequest.setIndexName(indexName);
        keyConditions.put("IsOpen", new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(new AttributeValue().withN("1")));
        // ProjectionExpression
        queryRequest.setProjectionExpression("OrderCreationDate, ProductCategory, ProductName, OrderStatus");
    } else if (indexName == "OrderCreationDateIndex") {
        System.out.println("\nUsing index: '" + indexName + "': Bob's orders that were placed after 01/31/2013.");
        System.out.println("Only the projected attributes are returned\n");
        queryRequest.setIndexName(indexName);
        keyConditions.put("OrderCreationDate", new Condition().withComparisonOperator(ComparisonOperator.GT).withAttributeValueList(new AttributeValue().withN("20130131")));
        // Select
        queryRequest.setSelect(Select.ALL_PROJECTED_ATTRIBUTES);
    } else {
        System.out.println("\nNo index: All of Bob's orders, by OrderId:\n");
    }
    queryRequest.setKeyConditions(keyConditions);
    QueryResult result = client.query(queryRequest);
    List<Map<String, AttributeValue>> items = result.getItems();
    Iterator<Map<String, AttributeValue>> itemsIter = items.iterator();
    while (itemsIter.hasNext()) {
        Map<String, AttributeValue> currentItem = itemsIter.next();
        Iterator<String> currentItemIter = currentItem.keySet().iterator();
        while (currentItemIter.hasNext()) {
            String attr = (String) currentItemIter.next();
            if (attr == "OrderId" || attr == "IsOpen" || attr == "OrderCreationDate") {
                System.out.println(attr + "---> " + currentItem.get(attr).getN());
            } else {
                System.out.println(attr + "---> " + currentItem.get(attr).getS());
            }
        }
        System.out.println();
    }
    System.out.println("\nConsumed capacity: " + result.getConsumedCapacity() + "\n");
}
Also used : Condition(com.amazonaws.services.dynamodbv2.model.Condition) AttributeValue(com.amazonaws.services.dynamodbv2.model.AttributeValue) QueryResult(com.amazonaws.services.dynamodbv2.model.QueryResult) QueryRequest(com.amazonaws.services.dynamodbv2.model.QueryRequest) HashMap(java.util.HashMap) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Table (com.amazonaws.services.dynamodbv2.document.Table)6 Item (com.amazonaws.services.dynamodbv2.document.Item)4 CreateTableRequest (com.amazonaws.services.dynamodbv2.model.CreateTableRequest)4 LocalSecondaryIndex (com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndex)4 ProvisionedThroughput (com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput)4 ArrayList (java.util.ArrayList)4 AttributeDefinition (com.amazonaws.services.dynamodbv2.model.AttributeDefinition)3 KeySchemaElement (com.amazonaws.services.dynamodbv2.model.KeySchemaElement)3 Projection (com.amazonaws.services.dynamodbv2.model.Projection)3 AmazonServiceException (com.amazonaws.AmazonServiceException)2 AmazonDynamoDB (com.amazonaws.services.dynamodbv2.AmazonDynamoDB)2 Index (com.amazonaws.services.dynamodbv2.document.Index)2 QueryOutcome (com.amazonaws.services.dynamodbv2.document.QueryOutcome)2 QuerySpec (com.amazonaws.services.dynamodbv2.document.spec.QuerySpec)2 UpdateItemSpec (com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec)2 ValueMap (com.amazonaws.services.dynamodbv2.document.utils.ValueMap)2 AttributeValue (com.amazonaws.services.dynamodbv2.model.AttributeValue)2 Condition (com.amazonaws.services.dynamodbv2.model.Condition)2 GlobalSecondaryIndex (com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndex)2 QueryRequest (com.amazonaws.services.dynamodbv2.model.QueryRequest)2