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

Time:10-04

I'm quite new DynamoDB sdk. I don't really know how can you query in a table in DynamoDB with the hashKey and rangeKey.

Table schema:

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

I'm using global secondary index GSI: bookAndUserIndex. Code snippet:

    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;
    }

How can I edit this code to filter/get also by user?

CodePudding user response:

You just need to add the range (sort) key to the expression:

   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;
    }

This is well documented in the AWS SDK for Java documentation.

  • Related