如何查询DynamoDB的哈希和范围键在java?



我是很新的DynamoDBsdk。我真的不知道你怎么能用hashKey和rangeKey在DynamoDB表中查询。

表模式:

1. Id (HK)
2. Book (GSI HK)
3. User (GSI RK)

我使用全局二级索引GSI: bookAndUserIndex。代码片段:

public Loan getByBookAndUser(String book, String user) {
Loan loan = null;
HashMap<String, AttributeValue> av = new HashMap<>();
av.put(":v1", new AttributeValue().withS(book));
DynamoDBQueryExpression<Loan> queryExp = new DynamoDBQueryExpression<Loan>()
.withIndexName("bookAndUserIndex")
.withKeyConditionExpression("book = :v1")
.withExpressionAttributeValues(av)
.withConsistentRead(false);
PaginatedQueryList<Loan> result = this.mapper.query(Loan.class, queryExp);
if (result.size() > 0) {
loan = result.get(0);
}
return loan;
}

如何编辑此代码以过滤/获取user?

您只需将range (sort)键添加到表达式:

public Loan getByBookAndUser(String book, String user) {
Loan loan = null;
HashMap<String, AttributeValue> av = new HashMap<>();
av.put(":v1", new AttributeValue().withS(book));
av.put(":user", new AttributeValue().withS(user));
DynamoDBQueryExpression<Loan> queryExp = new DynamoDBQueryExpression<Loan>()
.withIndexName("bookAndUserIndex")
.addExpressionAttributeNamesEntry("#user", "user")
.withKeyConditionExpression("book = :v1 AND #user = :user")
.withExpressionAttributeValues(av)
.withConsistentRead(false);
PaginatedQueryList<Loan> result = this.mapper.query(Loan.class, queryExp);
if (result.size() > 0) {
loan = result.get(0);
}
return loan;
}

这在AWS SDK for Java文档中有很好的记录。

相关内容

  • 没有找到相关文章

最新更新