Search code examples
javaamazon-web-servicesamazon-dynamodbamazon-dynamodb-index

How to get items from DynamoDb in Descending order with AWS Java SDK?


I have a table in AWS DynamoDB called accountantHistoric. It has a primary partition key (id) and a primary sort key (tenant_id). I also created another index, called "ExpirationDate". The sort key of this index is the "expirationDate"(String) attribute. What I want is: get the itens based in the storeId (this field is not a key) and the tenant_id in descending order based on the "expirationDate" (from newest to oldest). I am also making paginated.

I am trying with the code below, but it is not returning in descending order.

What do I have to change?

Thank you all!

public AccountantEmailHistoricInfo getHistoric(String storeId, int page, int countReg, int fixedPage) {
            Condition conditionStoreId = new Condition().withComparisonOperator(ComparisonOperator.EQ)
                    .withAttributeValueList(new AttributeValue().withS(storeId));

            Condition conditionTenantId = new Condition().withComparisonOperator(ComparisonOperator.EQ)
                    .withAttributeValueList(new AttributeValue().withS(TenantIdentifierLocalThread.getTenantIdentifier()));

            final DynamoDBScanExpression scanPageExpression = new DynamoDBScanExpression()
                    .withFilterConditionEntry("tenant_id", conditionTenantId)
                    .withFilterConditionEntry("storeId", conditionStoreId)
                    .withIndexName("ExpirationDate")
                    .withLimit(countReg);

            List<AccountantEmailHistoric> accountantEmailHistoricList = new ArrayList<>();
            int i = 0;

            do {
                ScanResultPage<AccountantEmailHistoric> scanPage = mapper.scanPage(AccountantEmailHistoric.class, scanPageExpression);
                scanPageExpression.setExclusiveStartKey(scanPage.getLastEvaluatedKey());

                if (i == page) {
                    accountantEmailHistoricList.addAll(scanPage.getResults());
                }
                i++;
            } while (scanPageExpression.getExclusiveStartKey() != null);

            final DynamoDBScanExpression scan = new DynamoDBScanExpression()
                    .withFilterConditionEntry("tenant_id", conditionTenantId)
                    .withFilterConditionEntry("storeId", conditionStoreId);

            AccountantEmailHistoricInfo info = new AccountantEmailHistoricInfo(accountantEmailHistoricList);
            info.setPage(fixedPage);
            info.setTotalRecords(mapper.scan(AccountantEmailHistoric.class, scan).size());
            return info;
        }

Solution

  • You need to query, rather than scan. Then you can indicate ScanIndexForward set to false.