Wednesday, September 14, 2022

DynamoDB query from Global Secondary Index with AWS 2.X

With AWS 2.X enhanced DynamoDB client, they have redesigned ‘DynamoDB mapper’ in the Java v1 SDK. In latest version, it requires the annotation @DynamoDbBean in POJO that identifies the class as being a DynamoDb mappable entity. Let's look at how to query Global Secondary Index(GSI).

Solution
Example POJO using DynamoDbBean:
       

    import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
    import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
    import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSecondaryPartitionKey;

    @DynamoDbBean
    public class Customer {

        private String identifier;
        private String name;
        private int age;


        @DynamoDbPartitionKey
        public String getIdentifier(){
            return this.identifier;
        }
        public void setIdentifier(String transactionID){
            this.identifier  = transactionID;
        }

        @DynamoDbSecondaryPartitionKey(indexNames = {"name-index"}) 
        public String getName(){
            return name;
        }
        public void setName(String name){
            this.name = name;
        }

        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }

    }

  

       
 
following is how you can query GSI using enhanced DynamoDB client.
       

	public void getCustomersByName(String name) {
		
		DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
		        .dynamoDbClient(ddb)
		        .build();
		
		DynamoDbTable customerTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class));
		
		
		DynamoDbIndex secIndex = customerTable.index("name-index");
        AttributeValue attVal = AttributeValue.builder().s(name).build();
        QueryConditional queryConditional = QueryConditional
                .keyEqualTo(Key.builder().partitionValue(attVal).build());

        Iterable> results =  secIndex.query(
                QueryEnhancedRequest.builder()
                        .queryConditional(queryConditional)
                        .build());
        
        results.forEach(page -> {
            List customers = page.items();
            for (Customer c: customers) {
                System.out.println(c.getName());
            }
        });
		
	}

       
       

 

No comments:

Post a Comment