[英]Boto3: insert data into dynamodb table
I have a DynamoDB table called events
and I want to put
the data into the table.我有一个名为
events
的 DynamoDB 表,我想put
数据放入表中。
My dynamodb table structure is given below我的dynamodb表结构如下
{
"partition_key": "user_id1111",
"sort_key": "version_1",
"attributes": {
"events": [
{
"t": "1614712316",
"a": "product_view",
"i": "1275"
},
...
...
...
]
}
}
I have 2 entries of data:我有2个数据条目:
entry1 = {
"t": 1607208938861,
"a": "product_add",
"i": "142320"
}
entry2 =
{
"M": {
"t": {
"N": "1607208938862"
},
"a": {
"S": "product_purchase"
},
"i": {
"S": "142318"
}
}
}
I want to insert there two entries into the dynamodb table.我想在 dynamodb 表中插入两个条目。
I know we can use BOTO3-Dynamodb-resource
to insert entry1
into the table我知道我们可以使用
BOTO3-Dynamodb-resource
将entry1
插入表中
I know we can use BOTO3-Dynamodb-client
to insert entry2
into the table我知道我们可以使用
BOTO3-Dynamodb-client
将entry2
插入表中
NOTE:笔记:
entry1
==> the data will always be in the format similar to dynamodb resource
entry1
==> 数据将始终采用类似于dynamodb resource
的格式
entry2
==> the data will always be in the format similar to dynamodb client
entry2
==> 数据将始终采用类似于dynamodb client
的格式
GOAL:目标:
using single boto3-resource
method( put-item
), I want to insert these two records into dynamodb table.使用单个
boto3-resource
方法( put-item
),我想将这两条记录插入到 dynamodb 表中。
MY FINAL OUTPUT IN THE DYNAMODB TABLE WILL BE SIMILAR TO BELOW我在 DYNAMODB 表中的最终 OUTPUT 将类似于下面
{
"partition_key": "user_id1111",
"sort_key": "version_1",
"attributes": {
"events": [
{
"t": 1607208938861,
"a": "product_add",
"i": "142320"
},
{
"t": 1607208938862,
"a": "product_purchase",
"i": "142318"
},
]
}
}
Can anyone suggest a solution for this?任何人都可以为此提出解决方案吗?
Basically I found a python library called dynamodb-json
: https://pypi.org/project/dynamodb-json/基本上我找到了一个名为
dynamodb-json
的 python 库: https://pypi.org/project/dynamodb-json/
this library helps us to convert dynamodb-json
format into python representation
.这个库帮助我们将
dynamodb-json
格式转换为python representation
。 then, we can directly use boto3-dynamodb-resource to put python representation of an entry into dynamodb.然后,我们可以直接使用 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},
}
)
The above code solves my problem.上面的代码解决了我的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.