DynamoDB 查询性能 - 唯一分区键与唯一分区+排序键

rav*_*ii1 5 amazon-dynamodb dynamodb-queries

假设我有一个名为“student_course”的 Dynamo DB 表。我想存储每个学生在大学学习的课程。一名学生可以同时选修多门课程,一门课程可以同时有多名学生。所以基本上它是一个多重映射。

我的数据访问模式只有一种用例 -

  1. 一次获取一名学生和一门课程的记录,即获取每个 StudentId 和 CourseId 组合的数据。保证对于学生 ID 和课程 ID 组合,只有一条可用记录。

为了实现这一点,我可以通过这两种方式存储数据 -

  1. 分区键 = {学生 ID},排序键 = {课程 ID}
  2. Partition-key = "studentId:{student-id}_courseId:{course-id}", sort-key 不存在

我的问题是 - 如果有任何差异,哪个查询会执行得更好?我应该选择哪一个而不是另一个,为什么?

Oh *_*oon 5

在性能设计方面DDBGet APIDDB 的毫秒级数据检索能力是关键,因此围绕此 API 设计数据是合乎逻辑的

带有分区键 + 排序键的表

Partition Key | Sort Key    
--------------+-------------
Course1       | Student1
Course1       | Student2
Run Code Online (Sandbox Code Playgroud)

优势:

  1. 能够使用Get API来获取单个记录,例如Partition Key获取Sort Key单个记录,其中分区键 =“Course1”且排序键 =“Student1”
  2. 能够使用仅通过例如获取分区键 =“Course1”的所有记录来Get API获取记录列表Partition Key

坏处:

  1. 如果您只知道Sort Key(即学生)而不知道Partition Key(即课程),则您将无法使用Get API仅通过Sort Key

注意:一般来说,ReadThroughputDDBGet API查询的效率(使得查询不会轻易遇到“Roof”异常)与Partition Key. 拥有并分布的分区键越多,性能就越好

仅具有分区键的表

Partition Key Only   
--------------------
Course1#Student1
Course1#Student2
Run Code Online (Sandbox Code Playgroud)

优势:

  1. 能够使用Get API获取单个记录,例如Partition Key获取单个记录,其中分区键 =“Course1#Student1”

坏处:

  1. 将无法Get API仅使用以下子集来获取记录列表,Partition key例如获取分区键 =“Course1”的记录列表

关于 GSI

注意:在表上添加全局二级索引以支持Get API使用备用键的调用是一种常见的情况,例如获取记录列表,其中GSI Partition Key= 课程名称

Partition Key Only   | Non Key Attribute (Course) For GSI
---------------------+---------------------------
Course1#Student1     | Course1
Course1#Student2     | Course1
Run Code Online (Sandbox Code Playgroud)

您最多可以有 20 个GSI索引(软限制),可以选择通过支持请求删除此限制

Partition Key Only   | Non Key Attribute (Course) For GSI | Lecturer (For GSI 2)
---------------------+------------------------------------+---------------------
Course1#Student1     | Course1                            | Lecturer1
Course1#Student2     | Course1                            | Lecturer1
Run Code Online (Sandbox Code Playgroud)

结论

如果性能是关键,我会设计一个表,使其具有尽可能多的唯一Partition Keys,即分区键 = Course1#Student1 VS 分区键 = Course1,排序键 = Student1

如果您需要通过备用键查询,请按需添加GSIs到表中

(历史上GSIs每个表限制为 5 个,并且必须在创建表时指定,但这些限制现已取消)