【问题标题】:How to sort DynamoDB query result without specifying range key value如何在不指定范围键值的情况下对 DynamoDB 查询结果进行排序
【发布时间】:2019-07-21 05:54:04
【问题描述】:

我正在构建一个 DynamoDB 表,并且遇到了关于如何最好地构建我的索引的问题。我有 3 个查询需要执行。

我的桌子:

AttributeDefinitions:
  # This is large groups that can have many events
  - AttributeName: groupId
    AttributeType: S
  # An event can have many actions
  - AttributeName: eventId
    AttributeType: S
  # Each item has a unique actionId
  - AttributeName: actionId
    AttributeType: S
  # Each item has a creation date
  - AttributeName: createdAt
    AttributeType: S
  # Some type I need to filter by (enum: trigger|task for example)
  - AttributeName: actionType
    AttributeType: S

# Main query to return items by action ID - that works fine
KeySchema:
  - AttributeName: groupId
    KeyType: HASH
  - AttributeName: actionId
    KeyType: RANGE

这些是我需要实现的 3 个查询:

  1. 获取单个项目

现在我用

做一个 getItem
Key: {
  groupId,
  actionId
}

效果很好。

  1. 通过 eventId 获取所有项目(操作)

SQL:

SELECT * FROM theTable WHERE eventId = 123

如果我做这个本地索引,那么效果很好:

KeySchema:
  - AttributeName: groupId
    KeyType: HASH
  - AttributeName: eventId
    KeyType: RANGE
  1. 获取所有按 createdAt 日期排序的 actionType='trigger' 且属于 groupId 的项目(与 eventId 无关)

SQL:

SELECT * FROM theTable WHERE actionType = 'trigger' AND groupId = 123 SORT BY createdAt

这是给我的问题。我想查询我的数据并按日期排序返回。但是我需要使用另一个字段作为我的范围进行查询。因此,如果我将 createdAt 添加为我的范围,我将无法使用 actionType 进行过滤。如果我使用 actionType 则没有排序。

我怎样才能最好地构造这个表?在数据量方面。可以有很多组 (groupId)。每个组可以有许多事件 (eventId)。但是每个事件可能只有

【问题讨论】:

  • 您现在使用的确切键条件表达式是什么?
  • @MatthewPope 您的问题帮助我更清楚地看到了我的问题 - 事实上,我可以在没有 createdAt 值的情况下进行查询,但不能使用我想要的过滤器。我已经编辑了问题。
  • 那么您是在询问如何在 DynamoDB 查询中指定排序,还是在询问如何设计您的表以启用您想要的查询?如果是后者,将查询列出为英语句子或 SQL 可能会对您有所帮助。
  • 我添加了一个 sql 来说明。我是否需要查询或索引结构方面的帮助取决于需要发生的事情。希望sql澄清一下?
  • 这是您唯一需要做的查询吗?如果还有其他的,你能把它们也列出来吗?使用 DynamoDB,您可以获得出色的性能,但代价是您需要在设计表时考虑到所有访问模式。

标签: amazon-dynamodb dynamodb-queries


【解决方案1】:

为了实现类似的查询 SELECT * FROM theTable WHERE actionType = 'trigger' AND groupId = 123 SORT BY createdAt 在 DynamoDB 中,您需要有一个哈希键为 groupId 和复合排序键为 actionTypeCreatedAt 的索引(可以预见,它是 actionType、分隔符,然后是 createdAt 日期)。

在您的索引中,数据将如下所示(假设排序键中的分隔符为“_”):

groupId | actionTypeCreatedAt
--------|------------------------------
    123 | trigger_2019-06-30T08:30:00Z
    123 | trigger_2019-07-05T23:00:00Z
    123 | trigger_2019-07-20T10:15:00Z
    123 | action2_2019-06-25T15:10:00Z
    123 | action2_2019-07-08T02:45:00Z

现在,要实现您想要的查询,您需要使用groupId = 123 AND begins_with(actionTypeCreatedAt, "trigger_") 的关键条件表达式。 DynamoDB 会自动按排序键对结果进行排序,由于所有查询结果都具有相同的actionType 前缀,因此结果将仅按createdAt 日期排序。

【讨论】:

  • Ahhh.. 所以当我把一个Item然后创建actionType,createdAt和actionTypeCreatedAt字段手动正确吗?
  • 是的,在将项目发送到 DynamoDB 之前,您必须在应用程序中填充该字段。
猜你喜欢
  • 1970-01-01
  • 2020-02-11
  • 2016-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多