글로벌 보조 인덱스로 작업: Java - Amazon DynamoDB

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

글로벌 보조 인덱스로 작업: Java

AWS SDK for Java Document API를 사용하여 하나 이상의 글로벌 보조 인덱스가 포함된 Amazon DynamoDB 테이블을 만들고, 테이블의 인덱스를 설명하고, 인덱스를 사용하여 쿼리를 수행할 수 있습니다.

다음은 테이블 작업의 일반적인 단계입니다.

  1. DynamoDB 클래스의 인스턴스를 만듭니다.

  2. 해당하는 요청 객체를 만들어 작업의 필수 및 선택적 파라미터를 제공합니다.

  3. 이전 단계에서 만든 클라이언트가 제공한 적절한 메서드를 호출합니다.

글로벌 보조 인덱스가 있는 테이블 생성

글로벌 보조 인덱스는 테이블을 만들 때 동시에 만들 수 있습니다. 이렇게 하려면 CreateTable을 사용하고 하나 이상의 글로벌 보조 인덱스에 대한 사양을 제공합니다. 다음에 예로 나오는 Java 코드는 날씨 데이터에 대한 정보를 담고 있는 테이블을 만듭니다. 파티션 키는 Location이고 정렬 키는 Date입니다. PrecipIndex라는 이름의 글로벌 보조 인덱스를 사용하면 다양한 위치의 강수 데이터에 빠르게 액세스할 수 있습니다.

다음은 DynamoDB Document API를 사용하여 글로벌 보조 인덱스가 있는 테이블을 생성하는 단계입니다.

  1. DynamoDB 클래스의 인스턴스를 만듭니다.

  2. CreateTableRequest 클래스 인스턴스를 만들어 요청 정보를 입력합니다.

    이때 입력해야 하는 정보는 테이블 이름, 기본 키, 그리고 프로비저닝된 처리량 값입니다. 글로벌 보조 인덱스의 경우 인덱스 이름, 프로비저닝된 처리량 설정, 인덱스 정렬 키의 속성 정의, 인덱스의 키 스키마, 속성 프로젝션을 제공해야 합니다.

  3. 요청 객체를 파라미터로 입력하여 createTable 메서드를 호출합니다.

다음 Java 코드 예는 앞의 단계를 보여줍니다. 이 코드는 글로벌 보조 인덱스(PrecipIndex)가 있는 테이블(WeatherData)을 생성합니다. 인덱스 파티션 키는 Date이고 정렬 키는 Precipitation입니다. 모든 테이블 속성이 인덱스로 프로젝션되지 않습니다. 이 인덱스를 쿼리하여 특정 날짜에 대한 날씨 데이터를 가져와서 필요에 따라 강수량을 기준으로 데이터를 정렬할 수 있습니다.

Precipitation은 해당 테이블의 키 속성이 아니므로 필요하지 않습니다. 그러나 Precipitation이 없는 WeatherData 항목은 PrecipIndex에 표시되지 않습니다.

AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); DynamoDB dynamoDB = new DynamoDB(client); // Attribute definitions ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<AttributeDefinition>(); attributeDefinitions.add(new AttributeDefinition() .withAttributeName("Location") .withAttributeType("S")); attributeDefinitions.add(new AttributeDefinition() .withAttributeName("Date") .withAttributeType("S")); attributeDefinitions.add(new AttributeDefinition() .withAttributeName("Precipitation") .withAttributeType("N")); // Table key schema ArrayList<KeySchemaElement> tableKeySchema = new ArrayList<KeySchemaElement>(); tableKeySchema.add(new KeySchemaElement() .withAttributeName("Location") .withKeyType(KeyType.HASH)); //Partition key tableKeySchema.add(new KeySchemaElement() .withAttributeName("Date") .withKeyType(KeyType.RANGE)); //Sort key // PrecipIndex GlobalSecondaryIndex precipIndex = new GlobalSecondaryIndex() .withIndexName("PrecipIndex") .withProvisionedThroughput(new ProvisionedThroughput() .withReadCapacityUnits((long) 10) .withWriteCapacityUnits((long) 1)) .withProjection(new Projection().withProjectionType(ProjectionType.ALL)); ArrayList<KeySchemaElement> indexKeySchema = new ArrayList<KeySchemaElement>(); indexKeySchema.add(new KeySchemaElement() .withAttributeName("Date") .withKeyType(KeyType.HASH)); //Partition key indexKeySchema.add(new KeySchemaElement() .withAttributeName("Precipitation") .withKeyType(KeyType.RANGE)); //Sort key precipIndex.setKeySchema(indexKeySchema); CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName("WeatherData") .withProvisionedThroughput(new ProvisionedThroughput() .withReadCapacityUnits((long) 5) .withWriteCapacityUnits((long) 1)) .withAttributeDefinitions(attributeDefinitions) .withKeySchema(tableKeySchema) .withGlobalSecondaryIndexes(precipIndex); Table table = dynamoDB.createTable(createTableRequest); System.out.println(table.getDescription());

DynamoDB에서 테이블을 만들고 테이블 상태가 ACTIVE로 설정될 때까지 기다려야 합니다. 그런 다음 테이블에 데이터 항목을 입력할 수 있습니다.

글로벌 보조 인덱스가 있는 테이블 설명

테이블의 글로벌 보조 인덱스에 관한 자세한 내용은 DescribeTable 단원을 참조하세요. 각 인덱스에 대해 인덱스의 이름, 키 스키마 및 프로젝션된 속성에 액세스할 수 있습니다.

다음은 테이블의 글로벌 보조 인덱스 정보에 액세스하는 단계입니다.

  1. DynamoDB 클래스의 인스턴스를 만듭니다.

  2. Table 클래스의 인스턴스를 만들어 사용할 인덱스를 표시합니다.

  3. Table 객체의 describe 메서드를 호출합니다.

다음 Java 코드 예는 앞의 단계를 보여줍니다.

AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); DynamoDB dynamoDB = new DynamoDB(client); Table table = dynamoDB.getTable("WeatherData"); TableDescription tableDesc = table.describe(); Iterator<GlobalSecondaryIndexDescription> gsiIter = tableDesc.getGlobalSecondaryIndexes().iterator(); while (gsiIter.hasNext()) { GlobalSecondaryIndexDescription gsiDesc = gsiIter.next(); System.out.println("Info for index " + gsiDesc.getIndexName() + ":"); Iterator<KeySchemaElement> kseIter = gsiDesc.getKeySchema().iterator(); while (kseIter.hasNext()) { KeySchemaElement kse = kseIter.next(); System.out.printf("\t%s: %s\n", kse.getAttributeName(), kse.getKeyType()); } Projection projection = gsiDesc.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를 사용할 수 있습니다. 인덱스 이름, 인덱스 파티션 키 및 정렬 키(있는 경우)의 쿼리 기준, 반환하려는 속성을 지정해야 합니다. 이 예제에서 인덱스는 PrecipIndex이고, 해당 파티션 키는 Date이고, 정렬 키는 Precipitation입니다. 인덱스 쿼리에서는 특정 날짜에 대해 강수량이 0보다 큰 모든 날씨 데이터를 반환합니다.

다음은 AWS SDK for Java Document API를 사용하여 글로벌 보조 인덱스를 쿼리하는 단계입니다.

  1. DynamoDB 클래스의 인스턴스를 만듭니다.

  2. Table 클래스의 인스턴스를 만들어 사용할 인덱스를 표시합니다.

  3. 쿼리할 인덱스에 대한 Index 클래스의 인스턴스를 만듭니다.

  4. Index 객체의 query 메서드를 호출합니다.

속성 이름 Date는 DynamoDB 예약어입니다. 따라서 KeyConditionExpression에서 표현식 속성 이름을 자리 표시자로 사용해야 합니다.

다음 Java 코드 예는 앞의 단계를 보여줍니다.

AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); DynamoDB dynamoDB = new DynamoDB(client); Table table = dynamoDB.getTable("WeatherData"); Index index = table.getIndex("PrecipIndex"); QuerySpec spec = new QuerySpec() .withKeyConditionExpression("#d = :v_date and Precipitation = :v_precip") .withNameMap(new NameMap() .with("#d", "Date")) .withValueMap(new ValueMap() .withString(":v_date","2013-08-10") .withNumber(":v_precip",0)); ItemCollection<QueryOutcome> items = index.query(spec); Iterator<Item> iter = items.iterator(); while (iter.hasNext()) { System.out.println(iter.next().toJSONPretty()); }