【问题标题】:Using a key condition expression that includes conditions on the sortkey (AWS DynamoDB with Serverless Framework)使用包含排序键条件的键条件表达式(AWS DynamoDB with Serverless Framework)
【发布时间】:2020-09-14 18:47:55
【问题描述】:

我想从一个具有 partitionKey = userID 和 sortKey = todoID 的 DynamoDB 表(“todosTable”)中只检索一项。

只是为了向您展示一些东西,下面有一个示例可以正确获取 userId=userId 的用户的所有待办事项

 async getAllTodos(userId: string): Promise<TodoItem[]>{

    const result = await this.docClient.query({
      TableName: this.todosTable,
      KeyConditionExpression: 'userId = :userId',
      ExpressionAttributeValues: {
        ':userId': userId
      }
    }).promise()
    return result.Items as TodoItem[]
  }

但这不是我想要的。我只想要一件物品。 根据文档,我将使用一个作用于主键(分区和/或排序键)的键条件表达式

所以我尝试这样做,但这是不正确的

async getTodoItem1(userId: string, todoId: string): Promise<TodoItem>{

    const result = await this.docClient.get({
      TableName: this.todosTable,
      KeyConditionExpression: 'userId = :userId',
      AND todId = :todoId,
      ExpressionAttributeValues: {
        ':userId': userId,
        ':todoId': todoId
      }
    }).promise()

    return result.Item
  }

有人可以帮我获取只检索一项的正确查询,其中分区键 = userID 和排序键 = todoID 吗?

在这种情况下使用 GlobalSecondaryIndex 的模式是否正确?

谢谢

【问题讨论】:

    标签: aws-lambda amazon-dynamodb serverless-framework dynamodb-queries


    【解决方案1】:

    您还需要将辅助键添加到KeyConditionExpression,应该如下所示:

    KeyConditionExpression: 'userId = :userId AND todoId = :todoId'
    

    排序键更灵活,允许进行其他操作,如BEGINS_WITHBETWEEN

    【讨论】:

    • 请注意,如果您的 KeyConditionExpression 最终是这样的 - 指定特定的分区键和排序键 - 那么您也可以使用更简单的 GetItem 请求而不是 Query,即对单个特定项目的请求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多