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

DynamoDB分页查询报错:提供的起始键无效问题排查

DynamoDB分页查询起始键无效问题解决

问题核心原因

查询GSI时,ExclusiveStartKey必须严格匹配GSI主键(GSI2PK+GSI2SK)的完整精确值,以下是常见问题点及解决办法:


1. 优先使用LastEvaluatedKey作为起始键

这是最可靠的方式,直接复用DynamoDB返回的上一页结束键,避免手动拼接出错。修改代码如下:

public async Task<(IEnumerable<UserManagementTable> Visitors, bool HasMore)> GetCheckedInVisitorsPaginatedByEventId(
    string eventId, Dictionary<string, AttributeValue>? exclusiveStartKey = null, int? limit = null, bool scanIndexForward = false)
{
    var keyConditionExpression = "GSI2PK = :eventId AND begins_with(GSI2SK, :isCheckedInPrefix)";
    var expressionAttributeValues = new Dictionary<string, AttributeValue>
    {
        { ":eventId", new AttributeValue(eventId) },
        { ":isCheckedInPrefix", new AttributeValue("TRUE#") }
    };

    var query = new QueryRequest
    {
        TableName = "user-management",
        IndexName = "GSI2",
        KeyConditionExpression = keyConditionExpression,
        ExpressionAttributeValues = expressionAttributeValues,
        ScanIndexForward = scanIndexForward,
        ExclusiveStartKey = exclusiveStartKey,
        Limit = limit ?? 100
    };

    var result = await _dynamoDBClient.QueryAsync(query);

    var data = _context.FromDocuments<UserManagementTable>(result.Items.Select(Document.FromAttributeMap));

    var hasMore = result.LastEvaluatedKey != null && result.LastEvaluatedKey.Any();

    return (data, hasMore);
}

调用逻辑:

  • 首次查询:不传exclusiveStartKey
  • 后续分页:将上一次查询返回的LastEvaluatedKey直接传入该参数

2. 若必须手动拼接起始键,需满足以下条件

如果坚持通过日期拼接GSI2SK,务必做到:

  • 格式完全匹配:传入的exclusiveStartCheckInDate必须和表中GSI2SK的日期部分完全一致,包括时区(如UTC的Z后缀)、分隔符(-/:)、位数(如时分秒是否保留)。可以先在DynamoDB控制台复制一条已存在的GSI2SK值,拆出日期部分作为测试值验证。
  • 类型严格一致:确认GSI2PK和GSI2SK在表中的数据类型为字符串(S),代码中传入的AttributeValue也必须是字符串类型(不能是数字或其他类型)。
  • 键名无拼写错误:ExclusiveStartKey中的键名GSI2PK、GSI2SK必须和GSI定义的主键名称完全一致(大小写敏感)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 12:41:14