读取 DynamoDB 中的最新记录

Read most recent records in DynamoDB

我在 DynamoDB 中有一个 table 结构如下:

我也有这样定义的 LSI:

我的问题是,我需要读取给定用户 ID 的所有产品的最新记录。例如,来自此查询的 return 示例可能是:

UserID Product AsOfDate
User1 Product1 1617816274
User1 Product2 1617816288

我的问题是,如果我使用 table 上的索引,我可以获得最新记录,但这并不能保证我会获得每个产品的记录,例如,我可以获得很多记录在我看到最近的 User1-Product2 之前,User1-Product1。

如果我使用 LSI,我可以获得按产品排序的给定 UserId 的记录,但我将被迫按 AsOfDate 对结果进行排序并读取整个结果集以获取最新的结果。

谢谢!

如果我理解您的要求,我认为您需要为该数据创建另一条记录。您想要的是每个 user/product 组合的单个 AsOfDate,其中 AsOfDate 是最近的。如果您添加一条以 UserIDProduct 为关键字的记录,那么您将分别拥有一条记录。要完成这项工作,您可能需要更改 table 结构以支持单一 table 设计模式(或将此数据存储在不同的 table 中)。在单个 table 设计中,您可能有这样的东西:

pk sk UserID Product AsOfDate
User1 Purchase|Product1|1617816274 User1 Product1 1617816274
User1 MostRecent|Product1 User1 Product1 1617816274
User1 Purchase|Product2|1617816274 User1 Product2 1617816274
User1 Purchase|Product2|1617816288 User1 Product2 1617816288
User1 MostRecent|Product2 User1 Product2 1617816288

然后,要获取您查询 pk = userId and begins_with(sk, 'MostRecent|') 的所有最新记录。要获取您查询 pk = userId and begins_with(sk, 'Purchase|') 的其他记录。您的访问模式要求可能会让您改变一些,但想法应该与此类似。

每当您进行新的“购买”时,您都会为其插入新行,并同时更新“最新”行(如果需要,您可以在事务中执行此操作,或者使用 DynamoDB 流来做那个更新)。