List of usage examples for com.amazonaws.services.dynamodbv2.model GlobalSecondaryIndex GlobalSecondaryIndex
GlobalSecondaryIndex
From source file:com.clicktravel.infrastructure.persistence.aws.dynamodb.manager.DynamoDbTemplateInfrastructureManager.java
License:Apache License
public void init() { for (final AbstractDynamoDbTemplate dynamoDbTemplate : dynamoDbTemplates) { final Collection<String> tablesPendingCreation = new ArrayList<>(); final DatabaseSchemaHolder databaseSchemaHolder = dynamoDbTemplate.databaseSchemaHolder(); for (final ItemConfiguration itemConfiguration : databaseSchemaHolder.itemConfigurations()) { if (VariantItemConfiguration.class.isAssignableFrom(itemConfiguration.getClass())) { continue; }/*from w ww. j a va2 s.c o m*/ final String tableName = databaseSchemaHolder.schemaName() + "." + itemConfiguration.tableName(); if (!tablesPendingCreation.contains(tableName) && !isTableCreated(tableName)) { final List<AttributeDefinition> attributeDefinitions = new ArrayList<>(); final PrimaryKeyDefinition primaryKeyDefinition = itemConfiguration.primaryKeyDefinition(); final String hashKey = primaryKeyDefinition.propertyName(); final ScalarAttributeType hashKeyType = getAttributeType(primaryKeyDefinition.propertyType()); attributeDefinitions.add( new AttributeDefinition().withAttributeName(hashKey).withAttributeType(hashKeyType)); final List<KeySchemaElement> keySchema = new ArrayList<>(); keySchema.add(new KeySchemaElement().withAttributeName(hashKey).withKeyType(KeyType.HASH)); if (CompoundPrimaryKeyDefinition.class.isAssignableFrom(primaryKeyDefinition.getClass())) { final CompoundPrimaryKeyDefinition compoundPrimaryKeyDefinition = (CompoundPrimaryKeyDefinition) primaryKeyDefinition; final String rangeKey = compoundPrimaryKeyDefinition.supportingPropertyName(); final ScalarAttributeType rangeKeyType = getAttributeType( compoundPrimaryKeyDefinition.supportingPropertyType()); attributeDefinitions.add(new AttributeDefinition().withAttributeName(rangeKey) .withAttributeType(rangeKeyType)); keySchema .add(new KeySchemaElement().withAttributeName(rangeKey).withKeyType(KeyType.RANGE)); } final Collection<GlobalSecondaryIndex> globalSecondaryIndexes = new ArrayList<>(); for (final IndexDefinition indexDefinition : itemConfiguration.indexDefinitions()) { final ScalarAttributeType attributeType = getAttributeType( primaryKeyDefinition.propertyType()); // if there are any indexes, we need to add attributes for them attributeDefinitions .add(new AttributeDefinition().withAttributeName(indexDefinition.propertyName()) .withAttributeType(attributeType)); final ProvisionedThroughput indexProvisionedThroughput = new ProvisionedThroughput() .withReadCapacityUnits((long) readThroughput) .withWriteCapacityUnits((long) writeThroughput); final GlobalSecondaryIndex globalSecondaryIndex = new GlobalSecondaryIndex() .withIndexName(indexDefinition.propertyName() + "_idx") .withProvisionedThroughput(indexProvisionedThroughput) .withProjection(new Projection().withProjectionType("ALL")); final ArrayList<KeySchemaElement> indexKeySchema = new ArrayList<KeySchemaElement>(); indexKeySchema.add(new KeySchemaElement().withAttributeName(indexDefinition.propertyName()) .withKeyType(KeyType.HASH)); globalSecondaryIndex.setKeySchema(indexKeySchema); globalSecondaryIndexes.add(globalSecondaryIndex); } final ProvisionedThroughput tableProvisionedThroughput = new ProvisionedThroughput() .withReadCapacityUnits((long) readThroughput) .withWriteCapacityUnits((long) writeThroughput); CreateTableRequest request = new CreateTableRequest().withTableName(tableName) .withAttributeDefinitions(attributeDefinitions).withKeySchema(keySchema) .withProvisionedThroughput(tableProvisionedThroughput); if (!globalSecondaryIndexes.isEmpty()) { request = request.withGlobalSecondaryIndexes(globalSecondaryIndexes); } logger.debug("Creating table " + tableName); createTable(request, globalSecondaryIndexes.isEmpty()); tablesPendingCreation.add(tableName); } // Create tables for unique constraints if (!itemConfiguration.uniqueConstraints().isEmpty()) { final String uniqueConstraintTableName = databaseSchemaHolder.schemaName() + "-indexes." + itemConfiguration.tableName(); if (!isTableCreated(uniqueConstraintTableName)) { final List<KeySchemaElement> keySchema = new ArrayList<>(); keySchema.add(new KeySchemaElement("property", KeyType.HASH)); keySchema.add(new KeySchemaElement("value", KeyType.RANGE)); final List<AttributeDefinition> attributeDefinitions = new ArrayList<>(); attributeDefinitions.add(new AttributeDefinition("property", ScalarAttributeType.S)); attributeDefinitions.add(new AttributeDefinition("value", ScalarAttributeType.S)); final ProvisionedThroughput tableProvisionedThroughput = new ProvisionedThroughput() .withReadCapacityUnits((long) readThroughput) .withWriteCapacityUnits((long) writeThroughput); final CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(uniqueConstraintTableName) .withAttributeDefinitions(attributeDefinitions).withKeySchema(keySchema) .withProvisionedThroughput(tableProvisionedThroughput); createTable(createTableRequest, true); tablesPendingCreation.add(uniqueConstraintTableName); } } } // Create table for sequences if (!databaseSchemaHolder.sequenceConfigurations().isEmpty()) { final String sequenceTableName = databaseSchemaHolder.schemaName() + "-sequences"; if (!isTableCreated(sequenceTableName)) { final ProvisionedThroughput sequenceProvisionedThroughput = new ProvisionedThroughput() .withReadCapacityUnits((long) readThroughput) .withWriteCapacityUnits((long) writeThroughput); final List<KeySchemaElement> keySchema = new ArrayList<>(); keySchema.add(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH)); final List<AttributeDefinition> attributeDefinitions = new ArrayList<>(); attributeDefinitions .add(new AttributeDefinition().withAttributeName("name").withAttributeType("S")); final CreateTableRequest request = new CreateTableRequest().withTableName(sequenceTableName) .withAttributeDefinitions(attributeDefinitions).withKeySchema(keySchema) .withProvisionedThroughput(sequenceProvisionedThroughput); logger.debug("Creating sequence table " + sequenceTableName); amazonDynamoDbClient.createTable(request); tablesPendingCreation.add(sequenceTableName); } } logger.debug("Waiting for table creation: " + tablesPendingCreation); final Collection<String> tableNames = new ArrayList<>(tablesPendingCreation); final long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() - startTime < TABLE_CREATION_TIMEOUT_MS) { for (final String tableName : tableNames) { if (isTableCreated(tableName)) { logger.debug("Table " + tableName + " successfully created"); tablesPendingCreation.remove(tableName); } try { Thread.sleep(1000); } catch (final InterruptedException e) { throw new IllegalStateException(e); } } if (tablesPendingCreation.size() == 0) { break; } tableNames.clear(); tableNames.addAll(tablesPendingCreation); } if (tablesPendingCreation.size() != 0) { throw new IllegalStateException( "Unable to create tables for DynamoDb template: " + tablesPendingCreation); } // Seed the sequences with their starting values if (!databaseSchemaHolder.sequenceConfigurations().isEmpty()) { final ScanRequest scanRequest = new ScanRequest(databaseSchemaHolder.schemaName() + "-sequences"); final ScanResult scanResult = amazonDynamoDbClient.scan(scanRequest); Map<String, AttributeValue> lastEvaluatedKey = null; final Map<String, Map<String, AttributeValue>> sequenceItems = new HashMap<>(); do { for (final Map<String, AttributeValue> item : scanResult.getItems()) { sequenceItems.put(item.get("name").getS(), item); } lastEvaluatedKey = scanResult.getLastEvaluatedKey(); } while (lastEvaluatedKey != null); for (final SequenceConfiguration sequenceConfiguration : databaseSchemaHolder .sequenceConfigurations()) { final Map<String, AttributeValue> sequenceItem = sequenceItems .get(sequenceConfiguration.sequenceName()); if (sequenceItem == null) { final Map<String, ExpectedAttributeValue> expectedResults = new HashMap<>(); expectedResults.put("name", new ExpectedAttributeValue(false)); final Map<String, AttributeValue> attributeMap = new HashMap<>(); attributeMap.put("name", new AttributeValue().withS(sequenceConfiguration.sequenceName())); attributeMap.put("currentValue", new AttributeValue() .withN(String.valueOf(sequenceConfiguration.startingValue() - 1))); final String tableName = databaseSchemaHolder.schemaName() + "-sequences"; final PutItemRequest itemRequest = new PutItemRequest().withTableName(tableName) .withItem(attributeMap).withExpected(expectedResults); amazonDynamoDbClient.putItem(itemRequest); } } } dynamoDbTemplate.initialize(amazonDynamoDbClient); } }
From source file:com.erudika.para.persistence.AWSDynamoUtils.java
License:Apache License
/** * Creates a table in AWS DynamoDB which will be shared between apps. * @param readCapacity read capacity// w w w .j a v a 2s . c o m * @param writeCapacity write capacity * @return true if created */ public static boolean createSharedTable(long readCapacity, long writeCapacity) { if (StringUtils.isBlank(SHARED_TABLE) || StringUtils.containsWhitespace(SHARED_TABLE) || existsTable(SHARED_TABLE)) { return false; } try { GlobalSecondaryIndex secIndex = new GlobalSecondaryIndex().withIndexName(getSharedIndexName()) .withProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L)) .withProjection(new Projection().withProjectionType(ProjectionType.ALL)).withKeySchema( new KeySchemaElement().withAttributeName(Config._APPID).withKeyType(KeyType.HASH), new KeySchemaElement().withAttributeName(Config._TIMESTAMP).withKeyType(KeyType.RANGE)); getClient().createTable(new CreateTableRequest().withTableName(getTableNameForAppid(SHARED_TABLE)) .withKeySchema(new KeySchemaElement(Config._KEY, KeyType.HASH)) .withAttributeDefinitions(new AttributeDefinition(Config._KEY, ScalarAttributeType.S), new AttributeDefinition(Config._APPID, ScalarAttributeType.S), new AttributeDefinition(Config._TIMESTAMP, ScalarAttributeType.S)) .withGlobalSecondaryIndexes(secIndex) .withProvisionedThroughput(new ProvisionedThroughput(readCapacity, writeCapacity))); } catch (Exception e) { logger.error(null, e); return false; } return true; }
From source file:com.exorath.service.party.service.DynamoDatabaseProvider.java
License:Apache License
/** * @param primKey Primary partition key for the table * @param gsi String array for global secondary index's, allow for searching on more than primary key * @return Table containing party information *///from w w w. ja v a 2s . c o m private Table setupTable(String primKey, String... gsi) { Table table; try { ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput(1L, 1L); ArrayList<GlobalSecondaryIndex> gsiArr = new ArrayList<>(); ArrayList<AttributeDefinition> attDefs = new ArrayList<>(); for (String g : gsi) { GlobalSecondaryIndex gsiIndex = new GlobalSecondaryIndex().withIndexName(g) .withProvisionedThroughput(provisionedThroughput) .withKeySchema(new KeySchemaElement().withAttributeName(g).withKeyType(KeyType.HASH)) .withProjection(new Projection().withProjectionType("ALL")); gsiArr.add(gsiIndex); attDefs.add(new AttributeDefinition(g, ScalarAttributeType.S)); } attDefs.add(new AttributeDefinition(primKey, ScalarAttributeType.S)); table = database.createTable(new CreateTableRequest().withTableName(tableName) .withKeySchema(new KeySchemaElement(primKey, KeyType.HASH)).withGlobalSecondaryIndexes(gsiArr) .withAttributeDefinitions(attDefs).withProvisionedThroughput(provisionedThroughput)); logger.info("Created DynamoDB table " + tableName + " with 1r/1w provisioning. Waiting for it to activate."); } catch (ResourceInUseException ex) { table = database.getTable(tableName); logger.info("DynamoDB table " + tableName + " already existed. Waiting for it to activate."); } try { table.waitForActive(); } catch (InterruptedException ex) { logger.error("DynamoDB table " + tableName + " could not activate!\n" + ex.getMessage()); System.exit(1); } logger.info("DynamoDB table " + tableName + " active."); return table; }
From source file:com.makariev.dynamodb.data.tables.creators.UserPreferenceCreator.java
License:Apache License
@Override public CreateTableRequest getCreateTableRequest() { final String tableName = UserPreference.TABLE_NAME; final String hashKeyName = "userNo"; final ScalarAttributeType hashKeyType = ScalarAttributeType.N; final Long readCapacityUnits = 10L; final Long writeCapacityUnits = 10L; //////////////// final CreateTableRequest request = basicTable(tableName, readCapacityUnits, writeCapacityUnits, hashKeyName, hashKeyType);/*from ww w . j a v a2 s.c om*/ //define GlobalSecondaryIndex request.getAttributeDefinitions().add( new AttributeDefinition().withAttributeName("firstName").withAttributeType(ScalarAttributeType.S)); request.getAttributeDefinitions().add( new AttributeDefinition().withAttributeName("lastName").withAttributeType(ScalarAttributeType.S)); // NameIndex final GlobalSecondaryIndex nameIndex = new GlobalSecondaryIndex().withIndexName(UserPreference.NAME_INDEX) .withProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(10L).withWriteCapacityUnits(10L)) .withProjection(new Projection().withProjectionType("ALL")); final List<KeySchemaElement> indexKeySchema = new ArrayList<>(); indexKeySchema.add(new KeySchemaElement().withAttributeName("firstName").withKeyType(KeyType.HASH)); indexKeySchema.add(new KeySchemaElement().withAttributeName("lastName").withKeyType(KeyType.RANGE)); nameIndex.setKeySchema(indexKeySchema); request.withGlobalSecondaryIndexes(nameIndex); return request; }
From source file:com.vivastream.security.oauth2.common.util.DynamoDBInitializationHelper.java
License:Apache License
public static void createTokenTables(AmazonDynamoDBClient client, DynamoDBTokenSchema schema) { GlobalSecondaryIndex gsiAuthenticationIdToken = new GlobalSecondaryIndex() // .withIndexName(schema.getAccessIndexAuthenticationId()) // .withKeySchema(new KeySchemaElement(schema.getAccessColumnAuthenticationId(), KeyType.HASH)) // .withProvisionedThroughput(DEFAULT_PROVISIONED_THROUGHPUT) // .withProjection(new Projection().withProjectionType(ProjectionType.KEYS_ONLY)); GlobalSecondaryIndex gsiRefreshToken = new GlobalSecondaryIndex() // .withIndexName(schema.getAccessIndexRefreshToken()) // .withKeySchema(new KeySchemaElement(schema.getAccessColumnRefreshToken(), KeyType.HASH)) // .withProvisionedThroughput(DEFAULT_PROVISIONED_THROUGHPUT) // .withProjection(new Projection().withProjectionType(ProjectionType.KEYS_ONLY)); GlobalSecondaryIndex gsiClientIdAndUserName = new GlobalSecondaryIndex() // .withIndexName(schema.getAccessIndexClientIdAndUserName()) // .withKeySchema( // new KeySchemaElement(schema.getAccessColumnClientId(), KeyType.HASH), // new KeySchemaElement(schema.getAccessColumnUserName(), KeyType.RANGE) // ) ////from www. j a va 2 s. c om .withProvisionedThroughput(DEFAULT_PROVISIONED_THROUGHPUT) // .withProjection(new Projection().withProjectionType(ProjectionType.KEYS_ONLY)); CreateTableRequest accessTableRequest = new CreateTableRequest() // .withTableName(schema.getAccessTableName()) // .withKeySchema(new KeySchemaElement(schema.getAccessColumnTokenId(), KeyType.HASH)) // .withGlobalSecondaryIndexes(gsiAuthenticationIdToken, gsiRefreshToken, gsiClientIdAndUserName) // .withAttributeDefinitions( new AttributeDefinition(schema.getAccessColumnTokenId(), ScalarAttributeType.S), // new AttributeDefinition(schema.getAccessColumnAuthenticationId(), ScalarAttributeType.S), // new AttributeDefinition(schema.getAccessColumnRefreshToken(), ScalarAttributeType.S), // new AttributeDefinition(schema.getAccessColumnClientId(), ScalarAttributeType.S), // new AttributeDefinition(schema.getAccessColumnUserName(), ScalarAttributeType.S) // ) // .withProvisionedThroughput(DEFAULT_PROVISIONED_THROUGHPUT) // ; CreateTableResult accessTableresponse = client.createTable(accessTableRequest); CreateTableRequest refreshTableRequest = new CreateTableRequest() // .withTableName(schema.getRefreshTableName()) // .withKeySchema(new KeySchemaElement(schema.getRefreshColumnTokenId(), KeyType.HASH)) // .withAttributeDefinitions( new AttributeDefinition(schema.getRefreshColumnTokenId(), ScalarAttributeType.S) // ) // .withProvisionedThroughput(DEFAULT_PROVISIONED_THROUGHPUT) // ; CreateTableResult refreshTableresponse = client.createTable(refreshTableRequest); }
From source file:io.venable.amazonaws.dynamo.table.builder.GlobalSecondaryIndexBuilderImpl.java
License:Apache License
public void buildSecondaryIndexes(Collection<GlobalSecondaryIndex> globalSecondaryIndexCollection, Collection<AttributeDefinition> attributeDefinitionCollection) { GlobalSecondaryIndex globalSecondaryIndex = new GlobalSecondaryIndex(); globalSecondaryIndex.setIndexName(indexName); Collection<KeySchemaElement> keySchemaElementCollection = new ArrayList<>(); buildKeys(keySchemaElementCollection, attributeDefinitionCollection); globalSecondaryIndex.setKeySchema(keySchemaElementCollection); projection.build(globalSecondaryIndex); setProvisionedThroughput(new GlobalSecondaryIndexProvisionedThroughputSetter(globalSecondaryIndex)); globalSecondaryIndexCollection.add(globalSecondaryIndex); }
From source file:jp.classmethod.aws.dynamodb.DynamoDbRepository.java
License:Open Source License
/** * Creates a GSI configuration object/*ww w . ja va2 s.co m*/ * * @param name name of the index object to create * @param hashKey hash key of the index * @param rangeKey range key of the index * @param nonKeyAttributes determines the projection type and top level projected attributes. * if null, ALL attributes are projected. if an empty list, KEYS_ONLY are projected. * if the list has elements, only the elements INCLUDED in the list are projected * @return a description of a global secondary index that can be used to create a table. */ protected static GlobalSecondaryIndex createGlobalSecondaryIndex(String name, String hashKey, String rangeKey, List<String> nonKeyAttributes) { Preconditions.checkArgument(false == Strings.isNullOrEmpty(hashKey)); final KeySchemaElement hks = new KeySchemaElement(hashKey, KeyType.HASH); final Projection projection; if (nonKeyAttributes == null) { projection = new Projection().withProjectionType(ProjectionType.ALL); } else if (nonKeyAttributes.isEmpty()) { projection = new Projection().withProjectionType(ProjectionType.KEYS_ONLY); } else { projection = new Projection().withProjectionType(ProjectionType.INCLUDE) .withNonKeyAttributes(nonKeyAttributes); } final GlobalSecondaryIndex result = new GlobalSecondaryIndex().withIndexName(name) .withProjection(projection); if (Strings.isNullOrEmpty(rangeKey)) { result.withKeySchema(hks); } else { result.withKeySchema(hks, new KeySchemaElement(rangeKey, KeyType.RANGE)); } return result; }
From source file:jp.classmethod.aws.dynamodb.DynamoDbRepository.java
License:Open Source License
/** * Create instance./* w ww . j a v a 2 s . c om*/ * * @param prefix the table prefix * @param tableNameSuffix the suffix for the table name * @param amazonDynamoDB dynamodb client * @param provisionedThroughputMap map of provisioned througput * @param objectMapper mapper to use for back/forth to json * @param clazz class reference of E * @param attributeDefinitions types of keys on base table and GSI * @param baseTableKeyNames names of base table keys * @param gsiList list of GSI definitions * @param versionString * @since #version# */ protected DynamoDbRepository(String prefix, String tableNameSuffix, AmazonDynamoDB amazonDynamoDB, Map<String, ProvisionedThroughput> provisionedThroughputMap, ObjectMapper objectMapper, Class<E> clazz, Map<String, ScalarAttributeType> attributeDefinitions, List<String> baseTableKeyNames, Map<String, GlobalSecondaryIndex> gsiList, String versionString) { Preconditions.checkNotNull(amazonDynamoDB); Preconditions.checkArgument(false == Strings.isNullOrEmpty(tableNameSuffix)); Preconditions.checkNotNull(provisionedThroughputMap); Preconditions.checkNotNull(attributeDefinitions); this.dynamoDB = amazonDynamoDB; this.tableNameSuffix = tableNameSuffix; final String tableName = Strings.isNullOrEmpty(prefix) ? tableNameSuffix : String.format(Locale.ENGLISH, "%s_%s", prefix, tableNameSuffix); this.table = new Table(this.dynamoDB, tableName); this.ptMap = provisionedThroughputMap; this.gsis = gsiList != null ? new HashMap<>() : null; this.definitions = new HashMap<>(attributeDefinitions); this.lookupKeyConditions = new HashMap<>(); this.objectMapper = objectMapper; this.clazz = clazz; this.gsiHashKeys = new HashMap<>(); this.gsiRangeKeys = new HashMap<>(); this.versionProperty = Strings.isNullOrEmpty(versionString) ? null : versionString; Optional.ofNullable(gsiList).orElse(new HashMap<>()).values().forEach(gsi -> { final String indexName = gsi.getIndexName(); //make a copy final GlobalSecondaryIndex copy = new GlobalSecondaryIndex().withIndexName(gsi.getIndexName()) .withKeySchema(gsi.getKeySchema()).withProjection(gsi.getProjection()) .withProvisionedThroughput(ptMap.get(indexName)); final String hk = copy.getKeySchema().get(0).getAttributeName(); final String rk = copy.getKeySchema().size() == 2 ? copy.getKeySchema().get(1).getAttributeName() : null; this.gsis.put(indexName, copy); this.gsiHashKeys.put(indexName, hk); if (rk != null) { lookupKeyConditions.put(indexName, String.format(Locale.ENGLISH, "%s = :%s and %s = :%s", hk, hk, rk, rk)); this.gsiRangeKeys.put(indexName, rk); } else { lookupKeyConditions.put(indexName, String.format(Locale.ENGLISH, "%s = :%s", hk, hk)); } }); Preconditions.checkNotNull(baseTableKeyNames); Preconditions.checkArgument(false == baseTableKeyNames.isEmpty(), "need at least one key"); Preconditions.checkArgument(baseTableKeyNames.size() <= 2, "cant have more than two keys (one partition and one sort key)"); //add the attribute definitions for the base table key schema baseTableKeyNames.stream().forEach(name -> Preconditions.checkArgument(this.definitions.containsKey(name))); this.schemata = Lists.newArrayList(new KeySchemaElement(baseTableKeyNames.get(0), KeyType.HASH)); if (baseTableKeyNames.size() == 2) { schemata.add(new KeySchemaElement(baseTableKeyNames.get(1), KeyType.RANGE)); } hashKeyName = schemata.get(0).getAttributeName(); rangeKeyName = schemata.size() == 2 ? schemata.get(1).getAttributeName() : null; conditionalCreateCondition = rangeKeyName != null ? String.format(Locale.ENGLISH, "attribute_not_exists(%s) and attribute_not_exists(%s)", hashKeyName, rangeKeyName) : String.format(Locale.ENGLISH, "attribute_not_exists(%s)", hashKeyName); conditionalDeleteCondition = rangeKeyName != null ? String.format(Locale.ENGLISH, "attribute_exists(%s) and attribute_exists(%s)", hashKeyName, rangeKeyName) : String.format(Locale.ENGLISH, "attribute_exists(%s)", hashKeyName); }
From source file:org.diksha.common.dyutils.SchedulerDynamoTable.java
License:Apache License
public void createDynamoTable(DynamoDB dynamoDB) { try {//from w w w.ja va 2 s. c om System.out.println(toString()); ArrayList<KeySchemaElement> keySchema = new ArrayList<KeySchemaElement>(); keySchema.add(new KeySchemaElement().withAttributeName(hashKeyName).withKeyType(KeyType.HASH)); ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<AttributeDefinition>(); attributeDefinitions .add(new AttributeDefinition().withAttributeName(hashKeyName).withAttributeType(hashKeyType)); if (rangeKeyType != null) { if (!rangeKeyType.isEmpty()) { attributeDefinitions.add(new AttributeDefinition().withAttributeName(rangeKeyName) .withAttributeType(rangeKeyType)); } } if (additionalAttributes.size() > 0) { for (int cnt = 0; cnt < additionalAttributes.size(); cnt++) { String[] args = (additionalAttributes.get(cnt).toString()).split(":"); if (args.length == 2) { attributeDefinitions.add( new AttributeDefinition().withAttributeName(args[0]).withAttributeType(args[1])); } } } CreateTableRequest request = new CreateTableRequest().withTableName(tableName).withKeySchema(keySchema) .withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(readCapacityUnits) .withWriteCapacityUnits(writeCapacityUnits)); ArrayList<LocalSecondaryIndex> localSecondaryIndexes = new ArrayList<LocalSecondaryIndex>(); ArrayList<GlobalSecondaryIndex> globalSecondaryIndexes = new ArrayList<GlobalSecondaryIndex>(); if (rangeKeyType != null) { if (!rangeKeyType.isEmpty()) { if (rangeKeyTypeGlobalOrLocal.equals("L")) { localSecondaryIndexes .add(new LocalSecondaryIndex().withIndexName(rangeKeyName + "-Index") .withKeySchema( new KeySchemaElement().withAttributeName(hashKeyName) .withKeyType(KeyType.HASH), new KeySchemaElement().withAttributeName(rangeKeyName) .withKeyType(KeyType.RANGE)) .withProjection( new Projection().withProjectionType(ProjectionType.KEYS_ONLY))); } else { globalSecondaryIndexes .add(new GlobalSecondaryIndex().withIndexName(rangeKeyName + "-Index") .withKeySchema( new KeySchemaElement().withAttributeName(hashKeyName) .withKeyType(KeyType.HASH), new KeySchemaElement().withAttributeName(rangeKeyName) .withKeyType(KeyType.RANGE)) .withProvisionedThroughput(new ProvisionedThroughput() .withReadCapacityUnits(indexReadCapacityUnits) .withWriteCapacityUnits(indexWriteCapacityUnits)) .withProjection( new Projection().withProjectionType(ProjectionType.KEYS_ONLY))); } } } if (indices.size() > 0) { for (int cnt = 0; cnt < indices.size(); cnt++) { SchedulerDynamoTableIndex schedulerDynamoTableIndex = indices.get(cnt); if (schedulerDynamoTableIndex.isGlobal()) { // System.out.println("IS GLOBAL"); globalSecondaryIndexes.add(schedulerDynamoTableIndex.getGlobalSecondaryIndex()); // System.out.println("size = " + globalSecondaryIndexes.size()); } } } if (localSecondaryIndexes.size() > 0) request.setLocalSecondaryIndexes(localSecondaryIndexes); if (globalSecondaryIndexes.size() > 0) request.setGlobalSecondaryIndexes(globalSecondaryIndexes); request.setAttributeDefinitions(attributeDefinitions); System.out.println("Issuing CreateTable request for " + tableName); Table table = dynamoDB.createTable(request); System.out.println("Waiting for " + tableName + " to be created...this may take a while..."); table.waitForActive(); } catch (Exception e) { System.err.println("CreateTable request failed for " + tableName); System.err.println(e.getMessage()); } }
From source file:org.iternine.jeppetto.dao.dynamodb.extra.TableBuilder.java
License:Apache License
public TableBuilder withGsi(String gsiHashKeyName, ScalarAttributeType gsiHashKeyType, String gsiRangeKeyName, ScalarAttributeType gsiRangeKeyType) { if (globalSecondaryIndexes == null) { globalSecondaryIndexes = new ArrayList<GlobalSecondaryIndex>(); }/* w w w. j av a2s . com*/ ArrayList<KeySchemaElement> keySchema = new ArrayList<KeySchemaElement>(); String indexName; attributeDefinitions.add(new AttributeDefinition(gsiHashKeyName, gsiHashKeyType)); keySchema.add(new KeySchemaElement().withKeyType(KeyType.HASH).withAttributeName(gsiHashKeyName)); if (gsiRangeKeyName != null) { attributeDefinitions.add(new AttributeDefinition(gsiRangeKeyName, gsiRangeKeyType)); keySchema.add(new KeySchemaElement().withKeyType(KeyType.RANGE).withAttributeName(gsiRangeKeyName)); indexName = gsiHashKeyName + "-" + gsiRangeKeyName; } else { indexName = gsiHashKeyName; } globalSecondaryIndexes.add(new GlobalSecondaryIndex().withIndexName(indexName) .withProvisionedThroughput(new ProvisionedThroughput(64L, 64L)).withKeySchema(keySchema) .withProjection(new Projection().withProjectionType(ProjectionType.ALL))); return this; }