로컬 보조 인덱스로 작업: Java
AWS SDK for Java Document API를 사용하여 하나 이상의 로컬 보조 인덱스가 포함된 Amazon DynamoDB 테이블을 만들고, 테이블의 인덱스를 설명하고, 인덱스를 사용하여 쿼리를 수행할 수 있습니다.
다음은 AWS SDK for Java Document API를 사용하여 테이블 작업을 할 때 따라야 할 공통 단계입니다.
-
DynamoDB클래스의 인스턴스를 만듭니다. -
해당하는 요청 객체를 만들어 작업의 필수 및 선택적 파라미터를 제공합니다.
-
이전 단계에서 만든 클라이언트가 제공한 적절한 메서드를 호출합니다.
로컬 보조 인덱스가 있는 테이블 생성
로컬 보조 인덱스는 테이블을 만들 때 동시에 만들어야 합니다. 이렇게 하려면 createTable 메서드를 사용하여 하나 이상의 로컬 보조 인덱스 사양을 입력합니다. 다음 Java 코드 예제는 보유한 음악 파일에 있는 곡의 정보를 담은 테이블을 만듭니다. 파티션 키는 Artist이고 정렬 키는 SongTitle입니다. 보조 인덱스인 AlbumTitleIndex는 앨범 제목을 사용해 쿼리를 쉽게 수행하는 데 사용합니다.
다음은 DynamoDB Document API를 사용하여 로컬 보조 인덱스가 있는 테이블을 생성하는 단계입니다.
-
DynamoDB클래스의 인스턴스를 만듭니다. -
CreateTableRequest클래스 인스턴스를 만들어 요청 정보를 입력합니다.이때 입력해야 하는 정보는 테이블 이름, 기본 키, 그리고 프로비저닝된 처리량 값입니다. 로컬 보조 인덱스의 경우 인덱스 이름, 인덱스 정렬 키의 이름 및 데이터 형식, 인덱스의 키 스키마, 속성 프로젝션을 입력해야 합니다.
-
요청 객체를 파라미터로 입력하여
createTable메서드를 호출합니다.
다음 Java 코드 예는 앞의 단계를 보여줍니다. 이 코드는 Music 속성에 보조 인덱스가 있는 테이블(AlbumTitle)을 생성합니다. 인덱스에 프로젝션되는 속성은 테이블 파티션 키 및 정렬 키와 인덱스 정렬 키뿐입니다.
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); DynamoDB dynamoDB = new DynamoDB(client); String tableName = "Music"; CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName); //ProvisionedThroughput createTableRequest.setProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits((long)5).withWriteCapacityUnits((long)5)); //AttributeDefinitions ArrayList<AttributeDefinition> attributeDefinitions= new ArrayList<AttributeDefinition>(); attributeDefinitions.add(new AttributeDefinition().withAttributeName("Artist").withAttributeType("S")); attributeDefinitions.add(new AttributeDefinition().withAttributeName("SongTitle").withAttributeType("S")); attributeDefinitions.add(new AttributeDefinition().withAttributeName("AlbumTitle").withAttributeType("S")); createTableRequest.setAttributeDefinitions(attributeDefinitions); //KeySchema ArrayList<KeySchemaElement> tableKeySchema = new ArrayList<KeySchemaElement>(); tableKeySchema.add(new KeySchemaElement().withAttributeName("Artist").withKeyType(KeyType.HASH)); //Partition key tableKeySchema.add(new KeySchemaElement().withAttributeName("SongTitle").withKeyType(KeyType.RANGE)); //Sort key createTableRequest.setKeySchema(tableKeySchema); ArrayList<KeySchemaElement> indexKeySchema = new ArrayList<KeySchemaElement>(); indexKeySchema.add(new KeySchemaElement().withAttributeName("Artist").withKeyType(KeyType.HASH)); //Partition key indexKeySchema.add(new KeySchemaElement().withAttributeName("AlbumTitle").withKeyType(KeyType.RANGE)); //Sort key Projection projection = new Projection().withProjectionType(ProjectionType.INCLUDE); ArrayList<String> nonKeyAttributes = new ArrayList<String>(); nonKeyAttributes.add("Genre"); nonKeyAttributes.add("Year"); projection.setNonKeyAttributes(nonKeyAttributes); LocalSecondaryIndex localSecondaryIndex = new LocalSecondaryIndex() .withIndexName("AlbumTitleIndex").withKeySchema(indexKeySchema).withProjection(projection); ArrayList<LocalSecondaryIndex> localSecondaryIndexes = new ArrayList<LocalSecondaryIndex>(); localSecondaryIndexes.add(localSecondaryIndex); createTableRequest.setLocalSecondaryIndexes(localSecondaryIndexes); Table table = dynamoDB.createTable(createTableRequest); System.out.println(table.getDescription());
DynamoDB에서 테이블을 만들고 테이블 상태가 ACTIVE로 설정될 때까지 기다려야 합니다. 그런 다음 테이블에 데이터 항목을 입력할 수 있습니다.
로컬 보조 인덱스가 있는 테이블 설명
테이블의 로컬 보조 인덱스에 관한 자세한 내용은 describeTable 메서드를 참조하세요. 각 인덱스에 대해 인덱스의 이름, 키 스키마 및 프로젝션된 속성에 액세스할 수 있습니다.
다음은 AWS SDK for Java Document API를 사용하여 테이블의 로컬 보조 인덱스 정보에 액세스하는 단계입니다.
-
DynamoDB클래스의 인스턴스를 만듭니다. -
Table클래스의 인스턴스를 만듭니다. 테이블 이름을 입력해야 합니다. -
describeTable객체의Table메서드를 호출합니다.
다음 Java 코드 예는 앞의 단계를 보여줍니다.
예
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); DynamoDB dynamoDB = new DynamoDB(client); String tableName = "Music"; Table table = dynamoDB.getTable(tableName); TableDescription tableDescription = table.describe(); List<LocalSecondaryIndexDescription> localSecondaryIndexes = tableDescription.getLocalSecondaryIndexes(); // This code snippet will work for multiple indexes, even though // there is only one index in this example. Iterator<LocalSecondaryIndexDescription> lsiIter = localSecondaryIndexes.iterator(); while (lsiIter.hasNext()) { LocalSecondaryIndexDescription lsiDescription = lsiIter.next(); System.out.println("Info for index " + lsiDescription.getIndexName() + ":"); Iterator<KeySchemaElement> kseIter = lsiDescription.getKeySchema().iterator(); while (kseIter.hasNext()) { KeySchemaElement kse = kseIter.next(); System.out.printf("\t%s: %s\n", kse.getAttributeName(), kse.getKeyType()); } Projection projection = lsiDescription.getProjection(); System.out.println("\tThe projection type is: " + projection.getProjectionType()); if (projection.getProjectionType().toString().equals("INCLUDE")) { System.out.println("\t\tThe non-key projected attributes are: " + projection.getNonKeyAttributes()); } }
로컬 보조 인덱스 쿼리
테이블을 Query할 때와 거의 동일한 방식으로 로컬 보조 인덱스에서 Query 작업을 사용할 수 있습니다. 인덱스 이름, 인덱스 정렬 키의 쿼리 기준, 반환하려는 속성을 지정해야 합니다. 이 예제에서 인덱스는 AlbumTitleIndex이고 인덱스 정렬 키는 AlbumTitle입니다.
인덱스로 프로젝션된 속성만 반환됩니다. 키가 아닌 속성을 선택하도록 이 쿼리를 수정할 수도 있지만, 그렇게 하려면 비교적 많은 비용이 드는 테이블 가져오기 작업이 필요합니다. 테이블 가져오기에 대한 자세한 내용은 속성 프로젝션 단원을 참조하세요.
다음은 AWS SDK for Java Document API를 사용하여 로컬 보조 인덱스를 쿼리하는 단계입니다.
-
DynamoDB클래스의 인스턴스를 만듭니다. -
Table클래스의 인스턴스를 만듭니다. 테이블 이름을 입력해야 합니다. -
Index클래스의 인스턴스를 만듭니다. 인덱스 이름을 입력해야 합니다. -
query클래스의Index메서드를 호출합니다.
다음 Java 코드 예는 앞의 단계를 보여줍니다.
예
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); DynamoDB dynamoDB = new DynamoDB(client); String tableName = "Music"; Table table = dynamoDB.getTable(tableName); Index index = table.getIndex("AlbumTitleIndex"); QuerySpec spec = new QuerySpec() .withKeyConditionExpression("Artist = :v_artist and AlbumTitle = :v_title") .withValueMap(new ValueMap() .withString(":v_artist", "Acme Band") .withString(":v_title", "Songs About Life")); ItemCollection<QueryOutcome> items = index.query(spec); Iterator<Item> itemsIter = items.iterator(); while (itemsIter.hasNext()) { Item item = itemsIter.next(); System.out.println(item.toJSONPretty()); }
로컬 보조 인덱스에서 일관된 읽기
최종적으로 일관된 읽기만 지원하는 글로벌 보조 인덱스와 달리, 로컬 보조 인덱스는 최종적으로 일관된 읽기와 강력하게 일관된 읽기를 모두 지원합니다. 로컬 보조 인덱스에서 강력히 일관된 읽기는 항상 업데이트된 최신 값을 반환합니다. 쿼리가 기본 테이블에서 추가 속성을 가져와야 하는 경우 가져온 해당 속성도 마찬가지로 인덱스와 일관성을 유지합니다.
기본적으로 Query는 최종적으로 일관된 읽기를 사용합니다. 강력하게 일관된 읽기를 요청하려면 QuerySpec에서 ConsistentRead를 true로 설정합니다. 다음 예제에서는 강력하게 일관된 읽기를 사용하여 AlbumTitleIndex를 쿼리합니다.
예
QuerySpec spec = new QuerySpec() .withKeyConditionExpression("Artist = :v_artist and AlbumTitle = :v_title") .withValueMap(new ValueMap() .withString(":v_artist", "Acme Band") .withString(":v_title", "Songs About Life")) .withConsistentRead(true);
참고
강력하게 일관된 읽기는 반환된(반올림된) 데이터 4KB당 하나의 읽기 용량 단위를 소비하는 반면, 최종적으로 일관된 읽기는 그중 절반을 소비합니다. 예를 들어 9KB의 데이터를 반환하는 강력하게 일관된 읽기는 3개의 읽기 용량 단위(9KB/4KB = 2.25, 반올림 3)를 사용하는 반면, 최종적으로 일관된 읽기를 사용하는 동일한 쿼리는 1.5개의 읽기 용량 단위를 사용합니다. 애플리케이션이 약간 오래된 데이터 읽기를 허용할 수 있는 경우 최종적으로 일관된 읽기를 사용하여 읽기 용량 사용량을 줄입니다. 자세한 내용은 읽기 용량 단위 섹션을 참조하세요.