来自DynamoDb的条件IN在Java上不起作用

问题描述

我正在将DynamoDBSpring Boot 2.1一起使用,并且在条件评估期间需要o子句IN时遇到错误。即使满足要求的行,查询结果也为空。

IN子句中明确显示结果后,如何从表中返回行?

public class DynamoRepository {

    private final DynamoDBMapper dynamoDBMapper;

    
    public Optional<List<USER>> query(String id) {
        Map<String,String> ean = new HashMap<>();
        ean.put("#status","status");

        Map<String,AttributeValue> eav = new HashMap<>();
        eav.put(":id",new AttributeValue().withS(documento));

        DynamoDBQueryExpression<USER> queryExpression = new DynamoDBQueryExpression<USER>()
            .withKeyConditionExpression("id = :id")
            .withFilterExpression("#status in (ACTIVE,PENDING)")
            .withExpressionAttributeNames(ean)
            .withExpressionAttributeValues(eav);

        List<USER> query = dynamoDBMapper.query(USER.class,queryExpression);

        return query.isEmpty() ? Optional.empty() : Optional.of(query);
    }

}

解决方法

过一会儿,我的解决方案是将状态的值定义为“表达式属性值”,如下面的代码

public class DynamoRepository {

    private final DynamoDBMapper dynamoDBMapper;

    
    public Optional<List<USER>> query(String id) {
        Map<String,String> ean = new HashMap<>();
        ean.put("#status","status");

        Map<String,AttributeValue> eav = new HashMap<>();
        eav.put(":id",new AttributeValue().withS(documento));
        eav.put(":active",new AttributeValue().withS("ACTIVE"));
        eav.put(":pending",new AttributeValue().withS("PENDING"));

        DynamoDBQueryExpression<USER> queryExpression = new DynamoDBQueryExpression<USER>()
            .withKeyConditionExpression("id = :id")
            .withFilterExpression("#status in (:active,:pending)")
            .withExpressionAttributeNames(ean)
            .withExpressionAttributeValues(eav);

        List<USER> query = dynamoDBMapper.query(USER.class,queryExpression);

        return query.isEmpty() ? Optional.empty() : Optional.of(query);
    }

}