【问题标题】:DynamoDB query performance with - a unique partition key vs a unique partition+sort keyDynamoDB 查询性能 - 唯一分区键与唯一分区+排序键
【发布时间】:2021-05-30 19:07:30
【问题描述】:

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

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

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

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

  1. 分区键 = {student-id},排序键 = {course-id}
  2. 分区键 = "studentId:{student-id}_courseId:{course-id}",排序键不存在

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

【问题讨论】:

    标签: amazon-dynamodb dynamodb-queries


    【解决方案1】:

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

    带有分区键 + 排序键的表

    Partition Key | Sort Key    
    --------------+-------------
    Course1       | Student1
    Course1       | Student2
    

    优势:

    1. 能够通过Partition KeySort Key 使用Get API 获取单个记录,例如获取 Partition Key = "Course1" 和 Sort Key = "Student1" 的单条记录
    2. 能够使用Get API 仅通过Partition Key 获取记录列表,例如获取 Partition Key = "Course1" 的所有记录

    缺点:

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

    注意:一般来说,DDB Get API 查询的效率(这样查询不会轻易命中ReadThroughput 异常“屋顶”)与Partition Key 的唯一性和分布密切相关。您拥有和分散的分区键越多,性能就越好

    只有分区键的表

    Partition Key Only   
    --------------------
    Course1#Student1
    Course1#Student2
    

    优势:

    1. 能够使用Get API 获取Partition Key 的单个记录,例如获取 Partition Key = "Course1#Student1" 的单条记录

    缺点:

    1. 将无法使用 Get API 获取仅使用 Partition key 子集的记录列表,例如获取 Partition Key = "Course1" 的记录列表

    关于 GSI

    注意:在表上添加 全局二级索引 以支持使用备用键的 Get API 调用是一种常见的场景,例如 Get a List of records where @987654342 @ = 课程名称

    Partition Key Only   | Non Key Attribute (Course) For GSI
    ---------------------+---------------------------
    Course1#Student1     | Course1
    Course1#Student2     | Course1
    

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

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

    结论

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

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

    (过去GSIs 被限制为每个表 5 个,并且必须在创建表时指定,但这些限制已被取消)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-17
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 1970-01-01
      • 2020-08-26
      相关资源
      最近更新 更多