1
votes

I have a table (Profile) with a Hash key (id), and I have a GSI on name, and a range key on country. I would like to create a DAO method which would fetch me all the records with a given value for name and country, something like this: List getProfileWithNameAndCountry(name, country);

Initially I was just searching the records using only name (GSI) using the following code and it worked perfectly:

Profile profile = new Profile();
profile.setCountry("name");
DynamoDBQueryExpression<Profile> queryExpression = new DynamoDBQueryExpression<Profile>()
                            .withIndexName("name-index")
                            .withHashKeyValues(profile)
                            .withConsistentRead(false);

But now I want to search using both name (GSI) and country (range key). I tried modifying the above code to this and it failed with an exception:

Profile profile = new Profile();
profile.setCountry("name");
Condition countryCondition = new Condition()
                    .withComparisonOperator(ComparisonOperator.EQ.toString())
                    .withAttributeValueList(new AttributeValue().withS(country));
DynamoDBQueryExpression<Profile> queryExpression = new DynamoDBQueryExpression<Profile>()
                            .withIndexName("name-index")
                            .withHashKeyValues(profile)
                            .withRangeKeyCondition("country", countryCondition)
                            .withConsistentRead(false);

I am really new to DynamoDB and I am not able to figure out how I can achieve this in java. Any help would be really appreciated.

1

1 Answers

0
votes

You can't combine hash key from the GSI with the range key of the table.

You need to create the GSI with both a hash and range key.