简体   繁体   中英

Query DynamoDB using a GSI and a range key

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM