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

时间:2019-07-20 19:24:15

标签: amazon-dynamodb dynamodb-queries

我正在构建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. 获取所有具有groupId(与eventId无关)的,按createdAt日期排序为actionType ='trigger'的项目

SQL:

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

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

如何最好地构造此表?在数据方面。可以有多个组(groupId)。每个组可以有许多事件(eventId)。但是每个事件可能只包含<100个动作(actionId)。

1 个答案:

答案 0 :(得分: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日期进行排序。