You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java DynamoDB Query中使用CONTAINS条件筛选数据?

在DynamoDB查询中添加CONTAINS筛选条件的实现方法

要在你的DynamoDB查询里添加CONTAINS筛选条件,你需要用到FilterExpression——这是DynamoDB用来在键条件查询之后过滤结果的表达式。CONTAINS可用于检查字符串是否包含指定子串,或者集合是否包含指定元素。

假设你要筛选description字段中包含"v3"的条目,以下是修改后的完整代码:

@Repository
public class DynamoDBRepo {

    @Resource(name = "dynamoDBMapper")
    DynamoDBMapper dbMapper;

    public List<ApiData> getDetails() {

        List<ApiData> listing = new ArrayList<>();
        QueryResultPage<ApiData> itemList;


        Map<String,String> expAttributeName = new HashMap<>();
        // 主键字段别名
        expAttributeName.put("#Id","Id");
        // 新增筛选字段的别名(避免与DynamoDB保留字冲突)
        expAttributeName.put("#desc", "description");

        Map<String, AttributeValue> expAttributeValue = new HashMap<>();
        // 主键查询值
        expAttributeValue.put(":Id",new AttributeValue().withS("Api_V3"));
        // 新增CONTAINS要匹配的子串值
        expAttributeValue.put(":searchStr", new AttributeValue().withS("v3"));


        DynamoDBQueryExpression<ApiData> retrieveQuery = new DynamoDBQueryExpression<ApiData>()
                .withKeyConditionExpression("#Id=:Id")
                // 新增FilterExpression,使用CONTAINS条件
                .withFilterExpression("CONTAINS(#desc, :searchStr)")
                .withExpressionAttributeNames(expAttributeName)
                .withExpressionAttributeValues(expAttributeValue)
                .withScanIndexForward(false);

        try {
            itemList = dbMapper.queryPage(ApiData.class, retrieveQuery);
            listing = itemList.getResults();
        }
        catch (ResourceArnNotFoundException e) {
            throw e;
        }
        catch (HttpServerErrorException e) {
            throw e;
        }
        catch (Exception e) {
            throw e;
        }
        return listing;
    }
}

关键改动说明:

  • 新增筛选字段的别名#desc,映射到实际字段名description,避免字段名与DynamoDB保留字冲突;
  • 添加筛选值:searchStr,对应要匹配的目标子串;
  • 通过withFilterExpression方法添加CONTAINS(#desc, :searchStr)表达式,实现包含匹配的筛选逻辑。

注意:FilterExpression是在键条件查询返回结果后进行过滤,不会减少DynamoDB的读取容量消耗,仅在返回给客户端前过滤不符合条件的数据。

内容的提问来源于stack exchange,提问作者alice menon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 13:41:12