Boto3:将数据插入 dynamodb table

Boto3: insert data into dynamodb table

我有一个名为 events 的 DynamoDB table,我想 put 将数据放入 table。

我的 dynamodb table 结构如下

{
 "partition_key": "user_id1111",
 "sort_key": "version_1",
 "attributes": {
  "events": [
   {
    "t": "1614712316",  
    "a": "product_view",   
    "i": "1275"
   },
   ...
   ...
   ...
  ]
 }
}

我有 2 个数据条目:

entry1 = {
     "t": 1607208938861,
     "a": "product_add",
     "i": "142320"
}
entry2 = 
    {
      "M": {
       "t": {
        "N": "1607208938862"
       },
       "a": {
        "S": "product_purchase"
       },
       "i": {
        "S": "142318"
       }
      }
     }

我想在 dynamodb 中插入两个条目 table。

我知道我们可以使用 BOTO3-Dynamodb-resourceentry1 插入 table

我知道我们可以使用 BOTO3-Dynamodb-cliententry2 插入 table

注意:

entry1 ==> 数据将始终采用类似于 dynamodb resource

的格式

entry2 ==> 数据将始终采用类似于 dynamodb client

的格式

目标:

使用单个boto3-resource方法(put-item),我想将这两条记录插入dynamodb table.

我在 DYNAMODB 中的最终输出 TABLE 将类似于以下内容

{
 "partition_key": "user_id1111",
 "sort_key": "version_1",
 "attributes": {
  "events": [
     {
     "t": 1607208938861,
     "a": "product_add",
     "i": "142320"
     },
     {
     "t": 1607208938862,
     "a": "product_purchase",
     "i": "142318"
     },

   
  ]
 }
}

有人可以为此提出解决方案吗?

基本上我找到了一个名为 dynamodb-json 的 python 库:https://pypi.org/project/dynamodb-json/

这个库帮助我们将 dynamodb-json 格式转换为 python representation。然后,我们可以直接使用 boto3-dynamodb-resource 将 python 表示的条目放入 dynamodb。

import boto3
import json
from dynamodb_json import json_util as dbjson


dynamodb = boto3.resource('dynamodb')
dbtable = dynamodb.Table('events')


entry1 = json.dumps({
     "t": 1607208938861,
     "a": "product_add",
     "i": "142320"
})

entry2 = 
    {
      "M": {
       "t": {
        "N": "1607208938862"
       },
       "a": {
        "S": "product_purchase"
       },
       "i": {
        "S": "142318"
       }
      }
     }


# convert entry2 into python representation
obj = json.dumps(dbjson.loads(entry2))

in_list = []
in_list.append(json.loads(entry1))
in_list.append(json.loads(obj))

response = dbtable.put_item(
           Item={
              "cache_key": "user_id1111",
              "sort_key": "version_1",
              "attributes": {"events":in_list},
     }
        )

上面的代码解决了我的问题。