使用包含排序键条件的键条件表达式(AWS DynamoDB with Serverless Framework)
Using a key condition expression that includes conditions on the sortkey (AWS DynamoDB with Serverless Framework)
我只想从 DynamoDB table(“todosTable”)中检索一项,其中 partitionKey = userID 和 sortKey = todoID。
只是为了向您展示一些东西,下面有一个示例可以正确获取 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[]
}
但这不是我想要的。我只想要一件商品。
根据文档,我将使用作用于主键的关键条件表达式(分区 and/or 排序键)
所以我尝试这样做,但这是不正确的
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 的模式是否正确?
谢谢
您还需要将辅助键添加到 KeyConditionExpression
,应该如下所示:
KeyConditionExpression: 'userId = :userId AND todoId = :todoId'
排序键更灵活,允许其他操作,如 BEGINS_WITH
、BETWEEN
等
我只想从 DynamoDB table(“todosTable”)中检索一项,其中 partitionKey = userID 和 sortKey = todoID。
只是为了向您展示一些东西,下面有一个示例可以正确获取 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[]
}
但这不是我想要的。我只想要一件商品。 根据文档,我将使用作用于主键的关键条件表达式(分区 and/or 排序键)
所以我尝试这样做,但这是不正确的
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 的模式是否正确?
谢谢
您还需要将辅助键添加到 KeyConditionExpression
,应该如下所示:
KeyConditionExpression: 'userId = :userId AND todoId = :todoId'
排序键更灵活,允许其他操作,如 BEGINS_WITH
、BETWEEN
等