DynamoDB基于排序键降序排列

时间:2019-03-22 10:04:07

标签: java spring spring-boot amazon-dynamodb dynamodb-queries

当前,我将Spring boot与DynamoDB一起使用,并将DynamoDBMapper用于所有数据库操作。现在,它基于排序键(字段名id)以升序排序。如何根据排序键值按降序排序?

当前代码:

@Override
public PageImpl<Order> getCustomerOrders(Pageable pageable) {

    List<Order> orders = new ArrayList<>();


    Map<String, AttributeValue> eav = new HashMap<String, AttributeValue>();


    DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
    List<String> exp = new ArrayList<>();


    // filters

    if (!exp.isEmpty())
        scanExpression
                .withFilterExpression(String.join(" AND ", exp)).withExpressionAttributeValues(eav);


    PaginatedScanList<Order> scan = mapper.scan(Order.class, scanExpression);




    int start = (int) pageable.getOffset();
    int size = scan.size();
    int end = (start + pageable.getPageSize()) > size ? size : (start + pageable.getPageSize());

    if (start < size)
        for (Order o : scan.subList(start, end)) {
            orders.add(o);
        }

    return new PageImpl<Order>(orders, pageable, size);
}

在进行一些谷歌搜索之后,我发现需要将ScanIndexForward设置为true,但是仍然感到困惑的是,如何使用DynamoDBMApper实现它?

还是我需要使用任何低级类,例如DynamoDB或AmazonDynamoDb?

1 个答案:

答案 0 :(得分:0)

最后,我自己找到了解决方案,感谢 @ydrall 的提示。根据他的评论,ScanIndexForward仅可与查询选项一起使用,因此我刚刚更新为query。我创建了DynamoDBQueryExpression对象,并使用setScanIndexForward方法(false)更新了属性。

完整的Java代码:

@Override
public PageImpl<Order> getAllProgramOrder(Pageable pageable, OrderFilter filter) {
    List<Order> orders = new ArrayList<>();


    DynamoDBQueryExpression<Order> queryExpression = new DynamoDBQueryExpression<Order>();

    queryExpression.setScanIndexForward(false);


    Map<String, AttributeValue> eav = new HashMap<String, AttributeValue>();
    eav.put(":val1", new AttributeValue().withS(authenticationFacade.getProgramId()));

    queryExpression.withKeyConditionExpression("hashKey = :val1 ")
            .withExpressionAttributeValues(eav);

    PaginatedQueryList<Order> scan = mapper.query(Order.class, queryExpression);


    int start = (int) pageable.getOffset();
    int size = scan.size();
    int end = (start + pageable.getPageSize()) > size ? size : (start + pageable.getPageSize());

    if (start < size)
        for (Order o : scan.subList(start, end)) {
            orders.add(o);
        }

    return new PageImpl<Order>(orders, pageable, size);
}

Ref:How can I Scan an index in reverse in DynamoDB?