【问题标题】:GROUP BY-Like query in DynamoDB with DynamoDbEnhancedClient使用 DynamoDbEnhancedClient 在 DynamoDB 中进行类似于 GROUP BY 的查询
【发布时间】:2022-11-24 06:18:52
【问题描述】:

我正在尝试使用类似于 SQL 中的 GROUP BY 的逻辑在 DynamoDB 中编写查询。让我们考虑下表,分区键为simulation_id

Simulation (Table):
   simulation_id_1 - type_1 - ...
   simulation_id_1 - type_1 - ...

   simulation_id_1 - type_2 - ...
   simulation_id_1 - type_2 - ...
   simulation_id_1 - type_2 - ...

   simulation_id_2 - type_2 - ...
   simulation_id_2 - type_2 - ...
   simulation_id_2 - type_2 - ...
   simulation_id_2 - type_2 - ...

   simulation_id_2 - type_3 - ...

结果将是:


simulation_id_1 - type_1 - 2 (count of entries)
simulation_id_1 - type_2 - 3
simulation_id_2 - type_2 - 4
simulation_id_2 - type_3 - 1

使用 DynamoDbEnhancedClient 实现该目标的最佳方法是什么?

【问题讨论】:

    标签: java amazon-dynamodb aws-java-sdk-2.x aws-java-sdk-dynamodb


    【解决方案1】:

    DynamoDB 不支持 GROUP BY 或 SUM 或任何其他类型的数学指标,并且在某种程度上被认为是一种反模式。

    话虽如此,有两种方法可以满足您的用例需求。

    1. 您可以执行Query操作并将Select参数设置为COUNTDOCS。这将返回与给定 simulationId 匹配的所有项目的计数,但是,这将需要 Query 读取与该 simulationId 相关的所有项目,仅返回计数。我相信它还需要您使用较低级别的客户端。
    2. 第二个选项是最有利的,使用 DynamoDB Streams 和 Lambda 函数为您保留 simulationId 的“聚合”记录。这意味着对于您添加或删除的每个项目,您都会增加或减少聚合记录。这将使您能够以高效且具有成本效益的方式获取所有记录的总和。
      PK SK Agg
      simulation_id_1 aggregate 3
      simulation_id_1 type1
      simulation_id_1 type2
      simulation_id_1 type3
      simulation_id_2 aggregate 1
      simulation_id_2 type1

    【讨论】:

      猜你喜欢
      • 2022-11-22
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 2019-01-06
      • 2014-03-11
      • 2022-08-18
      • 1970-01-01
      • 2016-10-11
      相关资源
      最近更新 更多