DynamoDB中的分页与全球二级指数

时间:2016-11-11 18:56:58

标签: node.js amazon-web-services pagination amazon-dynamodb

我的DynamoDB架构是:

TableName = 'Cities'
PrimaryIndex = '_id'
SecondaryIndex = 'areaId-timestamp-index'
  - areaId is primary key
  - timestamp is sort key

DynamoDB中的数据结构如下所示:

{ _id: '....', name: 'New York', areaId: 22, timestamp: 1478882557071 },
{ _id: '....', name: 'Washington', areaId: 22, timestamp: 1478882557071 },
{ _id: '....', name: 'Copenhagen', areaId: 18, timestamp: 1478882557071 },
{ _id: '....', name: 'Berlin', areaId: 12, timestamp: 1478882557071 },

我希望能够在以下条件下对城市进行分页:

  1. 只有来自,fx,id为22的区域的城市
  2. 必须根据时间戳
  3. 按顺序分页

    我的查询如下:

    const areaId = 22
    
    const params = {
      TableName: 'Cities',
      Limit: 10,
      IndexName: 'areaId-timestamp-index',
      KeyConditionExpression: 'areaId = :x',
      ExpressionAttributeValues: {
        ':x': areaId
      }
    }
    
    dynamo.query(params)
    

    当我运行此操作时,我会收到lastEvaluatedKey

    的预期回复
    LastEvaluatedKey = {
        areaId: 22,
        _id: '8c43-d917-f9ec',  // ID of last item in batch
        timestamp: 1478882561962  // Timestamp of last item in batch 
    }
    

    当我然后运行下一个后续查询(以获得更多结果)时,我添加ExclusiveStartKey属性,其值与LastEvaluatedKey中返回的值完全相同。

    但是,当我运行查询时,我得到:

    The provided key element does not match the schema
    

1 个答案:

答案 0 :(得分:0)

尝试将LastEvaluatedKey提供给ExclusiveStartKey,您必须以任何格式提供您收到的整个价值。

const areaId = 22
const params = {
  TableName: 'Cities',
  Limit: 10,
  LastEvaluatedKey:response.ExclusiveStartKey, // Get it from previous query respose and use in same format
  IndexName: 'areaId-timestamp-index',
  KeyConditionExpression: 'areaId = :x',
  ExpressionAttributeValues: {
    ':x': areaId
  }
}

希望这有帮助, 感谢