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

如何使用DynamoDB Java 2.x SDK仅按分区键查询主表?

使用DynamoDB Java 2.x SDK按分区键查询主表Products

以下是直接通过分区键查询Products主表的完整实现,和你已有的全局二级索引(GSI)查询逻辑核心区别在于:主表查询无需指定indexName,直接针对表的主键分区键构建条件即可。

完整代码示例

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import java.util.Map;

public class DynamoDbMainTableQuery {
    public static void main(String[] args) {
        // 用try-with-resources自动管理客户端资源,避免泄漏
        try (DynamoDbClient ddb = DynamoDbClient.builder()
                .region(Region.US_EAST_1) // 替换为你的AWS区域
                .build()) {

            // 替换为你的实际分区键名和要查询的值
            String partitionKey = "productId";
            String targetValue = "PROD-001";

            // 构建查询请求
            QueryRequest queryRequest = QueryRequest.builder()
                    .tableName("Products")
                    // 核心条件:分区键等于目标值
                    .keyConditionExpression(partitionKey + " = :pkValue")
                    // 绑定参数,避免表达式注入
                    .expressionValues(Map.of(
                            ":pkValue", AttributeValue.builder().s(targetValue).build()
                    ))
                    // 可选:指定只返回需要的字段,减少数据传输
                    // .projectionExpression("name, price, description")
                    .build();

            // 执行查询并获取结果
            QueryResponse response = ddb.query(queryRequest);

            // 遍历处理返回的产品列表
            response.items().forEach(productItem -> {
                // 提取具体字段示例(根据你的表结构调整)
                String productName = productItem.get("name").s();
                String productPrice = productItem.get("price").n();
                System.out.printf("产品名称: %s, 价格: %s%n", productName, productPrice);
            });

        } catch (Exception e) {
            System.err.println("查询出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

关键细节说明

  • 分区键类型适配:如果你的分区键是数字类型,将AttributeValue.builder().s(targetValue)替换为AttributeValue.builder().n(targetValue)即可
  • KeyConditionExpression:主表查询必须针对主键的分区键,不支持非主键字段的条件(这类场景才需要用GSI或扫描)
  • ProjectionExpression:按需指定返回字段可以显著提升查询性能,尤其当表字段较多时
  • 异常处理:实际生产环境中建议根据具体异常类型(如ResourceNotFoundException、ValidationException)做针对性处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 05:42:13