如何在java中通过Hash和Range Key查询DynamoDB?

How to query DynamoDB by Hash and Range Key in java?

我是新手 DynamoDB sdk。我真的不知道如何使用 hashKey 和 rangeKey 在 DynamoDB 中的 table 中查询。

Table 架构:

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 将此代码编辑为 filter/get?

您只需将范围(排序)键添加到表达式中:

   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 documentation 中有详细记录。