我正在构建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个查询:
现在我用
Key: {
groupId,
actionId
}
效果很好。
SQL:
SELECT * FROM theTable WHERE eventId = 123
如果我执行此本地索引,则效果很好:
KeySchema:
- AttributeName: groupId
KeyType: HASH
- AttributeName: eventId
KeyType: RANGE
SQL:
SELECT * FROM theTable WHERE actionType = 'trigger' AND groupId = 123 SORT BY createdAt
这是给我的问题。我想查询我的数据并返回按日期排序的数据。但是,我需要使用另一个字段作为RANGE进行查询。因此,如果我将createdAt添加为我的范围,则无法使用actionType进行过滤。如果我使用actionType,则没有排序。
我如何最好地构造这张桌子?在数据方面。可以有多个组(groupId)。每个组可以有许多事件(eventId)。但是每个事件可能只包含<100个动作(actionId)。
为了像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
日期对结果进行排序。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句