DynamoDB:如何创建具有嵌套JSON结构的表?

问题描述:

我想在dynamoDB中使用以下结构创建一个表。

I want to create a table in dynamoDB with below structure.

{
  "CartId": 123,
  "UserId": 356,
  "CartItems": [
    {
      "ProductId": 100,
      "Quantity": 50
    },
    {
      "ProductId": 121,
      "Quantity": 51
    }
  ]
}

在教程和文档中的每个地方都说,表中只能包含以下类型的属性:

Everywhere in tutorials and documents it says that we can only have below type of attributes in the table:


  1. 一组字符串

  1. Set of Strings

一组数字

二进制集

我想不出一种在DynamoDB中存储上述结构的方法。

I can't think of a way to store above structure in DynamoDB. Could you please help out?

我正在使用Java的对象映射器Api。如果您还可以告诉我,如何创建一个可以映射到此特定表结构的类,那就太好了。

I am using object mapper Api of java. It would be great if you can also tell me how can I create a class which can be mapped to this particular table structure.

从您提供的JSON结构来看,我认为您正在尝试使DynamoDB像关系数据库一样,而实际上您应该将DynamoDB视为简单的平面键值存储。因此,与其说像您建议的表结构,不如说它是扁平化的,并且顾客在购物车中的每个项目都有很多行。

From the JSON structure you gave, I think you are trying to make DynamoDB like a relational database, when really you should be thinking of DynamoDB as a simple flat key-value store. So instead of a table structure like you suggested, I would instead flatten it, and have many rows for each item the customer has in their cart.

例如

Primary hashkey (UserId) | Hash range key (CartId) | ProductId | Qty
356                        123                       100         50
356                        123                       121         51

您可以通过提供主键356和范围键123来获得购物车中的所有物品。这是DynamoDB存储可索引和可​​查询数据的方式。但是,这确实意味着您要存储两个单独的行。

In this way, you can get all items in a cart by providing a primary key of 356, with range key 123. This is the DynamoDB way of storing indexable and queryable data. This does mean you are storing two separate rows, however.

这种格式具有很多优点,特别是它使您可以在ProductId上创建本地二级索引来查找找出有多少客户将特定产品放入购物车。

A format like this has many advantages, in particular it enables you to create Local Secondary indices on the ProductId to find out how many customers put a particular product into their cart. It should also make it easy to see how the object mapper will work with this table structure.