Search code examples
amazon-web-servicesamazon-dynamodbamazon-mobile-hub

Querying Dynamo DB Indexes: GSI and LSI


I am using the mobile application to query Dynamo DB tables. I have used the below query to fetch an item from the Dynamo DB Test table:

Test t = mapper.load(Test.class, DynamoDBHashKey, DynamoDBRangeKey);

My question is how to query an item from a Global Secondary Index? I have defined the annotations and parameters correctly in the Java class of the Test table.

Is there any other method to query Global Secondary Indexes and the Local Secondary Indexes.


Solution

  • The load api cannot be used to query GSI. The Query API can be used to query the GSI with key attributes.

    Sample code:-

    Map<String, AttributeValue> vals = new HashMap<>();
                vals.put(":val1", new AttributeValue().withS("somevalue"));
    
    DynamoDBQueryExpression<modelclass> queryExp = new DynamoDBQueryExpression<modelclass>()
                        .withKeyConditionExpression("category = :val1").withIndexName("indexname")
                        .withExpressionAttributeValues(vals);
    
    dynamoDBMapper.query(modelclass.class, queryExp);
    

    DynamodbQueryExpression class