В этом посте мы создадим таблицы в базе данных DynamoDB Java-способом. Прежде чем начать, нам нужно установить локальную DynamodB, так как мы хотим избежать каких-либо затрат на использование DynamodB. Был предыдущий пост на местном динамоде.
Если вы используете Docker, вы можете найти локальное изображение DynamodB или вы можете создать его самостоятельно, как описано здесь . DynamoDB Java Java SDK дает нам возможность создавать таблицы DynamodB с использованием Java-кода.
Основное действие — создать таблицу с хеш-ключом. В этом случае электронная почта пользователя будет хеш-ключом.
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
|
List<KeySchemaElement> elements = new ArrayList<KeySchemaElement>(); KeySchemaElement keySchemaElement = new KeySchemaElement() .withKeyType(KeyType.HASH) .withAttributeName("email"); elements.add(keySchemaElement); List<AttributeDefinition> attributeDefinitions = new ArrayList<>(); attributeDefinitions.add(new AttributeDefinition() .withAttributeName("email") .withAttributeType(ScalarAttributeType.S)); CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName("Users") .withKeySchema(elements) .withProvisionedThroughput(new ProvisionedThroughput() .withReadCapacityUnits(5L) .withWriteCapacityUnits(5L)) .withAttributeDefinitions(attributeDefinitions); amazonDynamoDB.createTable(createTableRequest); |
Мы создали таблицу Users, используя его электронную почту для хеш-ключа. Следующая таблица будет называться Logins. Логины должны отслеживать каждый раз, когда пользователь входит в систему. Для этого, кроме использования хеш-ключа, мы также будем использовать клавишу диапазона.
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
List<KeySchemaElement> elements = new ArrayList<KeySchemaElement>(); KeySchemaElement hashKey = new KeySchemaElement() .withKeyType(KeyType.HASH) .withAttributeName("email"); KeySchemaElement rangeKey = new KeySchemaElement() .withKeyType(KeyType.RANGE) .withAttributeName("timestamp"); elements.add(hashKey); elements.add(rangeKey); List<AttributeDefinition> attributeDefinitions = new ArrayList<>(); attributeDefinitions.add(new AttributeDefinition() .withAttributeName("email") .withAttributeType(ScalarAttributeType.S)); attributeDefinitions.add(new AttributeDefinition() .withAttributeName("timestamp") .withAttributeType(ScalarAttributeType.N)); CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName("Logins") .withKeySchema(elements) .withProvisionedThroughput(new ProvisionedThroughput() .withReadCapacityUnits(5L) .withWriteCapacityUnits(5L)) .withAttributeDefinitions(attributeDefinitions); amazonDynamoDB.createTable(createTableRequest); |
Используя электронную почту в качестве хеш-ключа, мы можем запросить логины конкретного пользователя. Используя дату, когда вход произошел в качестве ключа диапазона, можно найти сортировку записей входа или выполнить расширенные запросы на основе даты входа для конкретного пользователя.
Однако в большинстве случаев ключ хеша и ключ диапазона недостаточны для наших нужд. DynamoDB предоставляет нам глобальные вторичные индексы и локальные вторичные индексы.
Мы создадим таблицу SupervisorS. Хеш-ключом Supervisor будет его имя. Руководитель будет работать на компанию. Компания будет нашим глобальным вторичным индексом. Поскольку компании владеют более чем одной фабрикой, полевая фабрика будет ключевым параметром.
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
List<KeySchemaElement> elements = new ArrayList<>(); KeySchemaElement hashKey = new KeySchemaElement() .withKeyType(KeyType.HASH) .withAttributeName("name"); elements.add(hashKey); List<GlobalSecondaryIndex> globalSecondaryIndices = new ArrayList<>(); ArrayList<KeySchemaElement> indexKeySchema = new ArrayList<>(); indexKeySchema.add(new KeySchemaElement() .withAttributeName("company") .withKeyType(KeyType.HASH)); //Partition key indexKeySchema.add(new KeySchemaElement() .withAttributeName("factory") .withKeyType(KeyType.RANGE)); //Sort key GlobalSecondaryIndex factoryIndex = new GlobalSecondaryIndex() .withIndexName("FactoryIndex") .withProvisionedThroughput(new ProvisionedThroughput() .withReadCapacityUnits((long) 10) .withWriteCapacityUnits((long) 1)) .withKeySchema(indexKeySchema) .withProjection(new Projection().withProjectionType(ProjectionType.ALL)); globalSecondaryIndices.add(factoryIndex); List<AttributeDefinition> attributeDefinitions = new ArrayList<>(); attributeDefinitions.add(new AttributeDefinition() .withAttributeName("name") .withAttributeType(ScalarAttributeType.S)); attributeDefinitions.add(new AttributeDefinition() .withAttributeName("company") .withAttributeType(ScalarAttributeType.S)); attributeDefinitions.add(new AttributeDefinition() .withAttributeName("factory") .withAttributeType(ScalarAttributeType.S)); CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName("Supervisors") .withKeySchema(elements) .withProvisionedThroughput(new ProvisionedThroughput() .withReadCapacityUnits(5L) .withWriteCapacityUnits(5L)) .withGlobalSecondaryIndexes(factoryIndex) .withAttributeDefinitions(attributeDefinitions); amazonDynamoDB.createTable(createTableRequest); |
Следующей таблицей будет таблица компаний. Ключом хэша будет родительская компания, а ключом диапазона — дочерняя компания. У каждой компании есть генеральный директор. Генеральный директор будет ключом диапазона для локального вторичного индекса.
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
List<KeySchemaElement> elements = new ArrayList<>(); KeySchemaElement hashKey = new KeySchemaElement() .withKeyType(KeyType.HASH) .withAttributeName("name"); KeySchemaElement rangeKey = new KeySchemaElement() .withKeyType(KeyType.RANGE) .withAttributeName("subsidiary"); elements.add(hashKey); elements.add(rangeKey); List<LocalSecondaryIndex> localSecondaryIndices = new ArrayList<>(); ArrayList<KeySchemaElement> indexKeySchema = new ArrayList<>(); indexKeySchema.add(new KeySchemaElement() .withAttributeName("name") .withKeyType(KeyType.HASH)); indexKeySchema.add(new KeySchemaElement() .withAttributeName("ceo") .withKeyType(KeyType.RANGE)); LocalSecondaryIndex ceoIndex = new LocalSecondaryIndex() .withIndexName("CeoIndex") .withKeySchema(indexKeySchema) .withProjection(new Projection().withProjectionType(ProjectionType.ALL)); localSecondaryIndices.add(ceoIndex); List<AttributeDefinition> attributeDefinitions = new ArrayList<>(); attributeDefinitions.add(new AttributeDefinition() .withAttributeName("name") .withAttributeType(ScalarAttributeType.S)); attributeDefinitions.add(new AttributeDefinition() .withAttributeName("subsidiary") .withAttributeType(ScalarAttributeType.S)); attributeDefinitions.add(new AttributeDefinition() .withAttributeName("ceo") .withAttributeType(ScalarAttributeType.S)); CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName("Companies") .withKeySchema(elements) .withProvisionedThroughput(new ProvisionedThroughput() .withReadCapacityUnits(5L) .withWriteCapacityUnits(5L)) .withLocalSecondaryIndexes(localSecondaryIndices) .withAttributeDefinitions(attributeDefinitions); amazonDynamoDB.createTable(createTableRequest); |
Вы можете найти исходный код на github .
| Ссылка: | Создавайте таблицы DynamoDB с Java от нашего партнера по JCG Эммануила Гкациоураса в блоге gkatzioura . |