问题描述
我有一个带有哈希键(id)的表(Profile),并且在名称上具有GSI,在国家/地区上具有范围键。 我想创建一个DAO方法,该方法将获取具有给定名称和国家/地区值的所有记录,如下所示:List getProfileWithNameAndCountry(name,country);
最初,我只是使用以下代码仅使用名称(GSI)搜索记录,并且效果很好:
Profile profile = new Profile();
profile.setCountry("name");
DynamoDBQueryExpression<Profile> queryExpression = new DynamoDBQueryExpression<Profile>()
.withIndexName("name-index")
.withHashkeyvalues(profile)
.withConsistentRead(false);
但是现在我想同时使用名称(GSI)和国家(范围键)进行搜索。我尝试将上面的代码修改为此,但是失败,并出现以下异常:
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);
我真的是DynamoDB的新手,我无法弄清楚如何用Java实现这一点。 任何帮助将不胜感激。
解决方法
您不能将GSI中的哈希键与表格的范围键结合使用。
您需要同时创建带有哈希键和范围键的GSI。