如何在不指定范围键值的情况下对 DynamoDB 查询结果进行排序

How to sort DynamoDB query result without specifying range key value

我正在构建一个 DynamoDB table 并且 运行 正在研究如何最好地构建我的索引的问题。我有 3 个查询需要执行。

我的Table:

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. 获取所有 actionType='trigger' 按 createdAt 日期排序且属于 groupId 的项目(不考虑 eventId)

SQL:

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

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

我怎样才能最好地构建这个 table?在数据量方面。可以有很多组(groupId)。每个组可以有很多事件(eventId)。但是每个事件很可能只有 <100 个动作 (actionId)。

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

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

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 日期排序。