首页 > 解决方案 > DynamoDb 获取项目键上的条件数无效

问题描述

我一直试图找到这种情况的解释,但我没有找到任何解释。我有两个 DynamoDb 表,都有两个键索引,一个是 HASH 键,另一个是 RANGE 键。

在两个键都是字符串的表中,我可以像这样仅使用 HASH 键查询数据库(使用节点 sdk):

  const params = {
    TableName: process.env.DYNAMODB_TABLE,
    Key: { id: sessionId },
  };
  const { Item } = await dynamoDb.get(params);

但是,另一个表上的相同操作会引发上述错误The number of conditions on the keys is invalid

这是两个表模式:

这个表定义允许我使用提到的查询。

  SessionsDynamoDbTable:
    Type: 'AWS::DynamoDB::Table'
    DeletionPolicy: Retain
    Properties:
      AttributeDefinitions:
        -
          AttributeName: userId
          AttributeType: S
        -
          AttributeName: id
          AttributeType: S
        -
          AttributeName: startDate
          AttributeType: S
      KeySchema:
        -
          AttributeName: userId
          KeyType: HASH
        -
          AttributeName: id
          KeyType: RANGE
      LocalSecondaryIndexes:
        - IndexName: byDate
          KeySchema:
          - AttributeName: userId
            KeyType: HASH
          - AttributeName: startDate
            KeyType: RANGE
          Projection:
            NonKeyAttributes:
            - endDate
            - name
            ProjectionType: INCLUDE
      BillingMode: PAY_PER_REQUEST
      TableName: ${self:provider.environment.DYNAMODB_TABLE}

这不允许我像提到的那样进行查询

  SessionsTable:
    Type: 'AWS::DynamoDB::Table'
    TimeToLiveDescription:
      AttributeName: expiresAt
      Enabled: true
    Properties:
      AttributeDefinitions:
        -
          AttributeName: id
          AttributeType: S
        -
          AttributeName: expiresAt
          AttributeType: N
      KeySchema:
        -
          AttributeName: id
          KeyType: HASH
        -
          AttributeName: expiresAt
          KeyType: RANGE
      BillingMode: PAY_PER_REQUEST
      TableName: ${self:provider.environment.DYNAMODB_TABLE}

我将整个表定义包括在内,因为我不知道二级索引是否会对这个问题产生影响。

标签: node.jsamazon-dynamodb

解决方案


您必须提供分区键属性的名称和该属性的单个值。查询返回具有该分区键值的所有项目。或者,您可以提供排序键属性并使用比较运算符来优化搜索结果。更多的

get (params, callback) ⇒ AWS.Request通过委托给 AWS.DynamoDB.getItem()
返回具有给定主键的项目的一组属性。

在 SessionsTableid中是 HASH 键,在 SessionsDynamoDbTableid中是 RANGE 键。对于 SessionsDynamoDbTable,除了 RANGE 键之外,您还应该提供 HASH 键。


推荐阅读