Reputation: 629
I have a DynamoDB table called events
and I want to put
the data into the table.
My dynamodb table structure is given below
{
"partition_key": "user_id1111",
"sort_key": "version_1",
"attributes": {
"events": [
{
"t": "1614712316",
"a": "product_view",
"i": "1275"
},
...
...
...
]
}
}
I have 2 entries of data:
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.
I know we can use BOTO3-Dynamodb-resource
to insert entry1
into the table
I know we can use BOTO3-Dynamodb-client
to insert entry2
into the table
NOTE:
entry1
==> the data will always be in the format similar to dynamodb resource
entry2
==> the data will always be in the format similar to dynamodb client
GOAL:
using single boto3-resource
method(put-item
), I want to insert these two records into dynamodb table.
MY FINAL OUTPUT IN THE DYNAMODB TABLE WILL BE SIMILAR TO BELOW
{
"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?
Upvotes: 0
Views: 7841
Reputation: 629
Basically I found a python library called dynamodb-json
: https://pypi.org/project/dynamodb-json/
this library helps us to convert dynamodb-json
format into python representation
. then, we can directly use boto3-dynamodb-resource to put python representation of an entry into 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.
Upvotes: 1