许多场景需要您使用 JSON 格式的数据,并且您希望提取并处理数据,然后将其保存到表中以供将来使用
在本文中,我们将讨论使用 Lambda 函数将 JSON 格式的数据从 S3 存储桶加载到 DynamoDB 表
先决条件
- 有权将对象上传到 S3
- 具有 S3 和 DynamoDB 权限的 Lambda 执行角色
架构和组件
下面的架构显示我们正在使用 3 个 AWS 服务
- S3 存储桶
- Lambda 函数
- DynamoDB 表
以下服务的简要说明作为茶点:
- S3 Bucket:具有可扩展性、安全性和高性能的对象存储服务将作为我们的数据存储服务
- Lambda 函数:无服务器计算服务,允许您运行代码而无需担心基础设施,易于设置并支持多种编程语言,我们将利用它来运行我们的代码并部署我们的逻辑。
- DynamoDB:无服务器 NoSQL 数据库,用于将我们的数据存储在表中,我们将使用它来存储 Lambda 函数处理后的数据
流动
- 用户将通过后台 PutObject API 的控制台或 CLI 将 JSON 文件上传到 S3 存储桶
- 对象上传成功,将触发S3事件调用lambda函数来加载和处理文件
- Lambda 将处理数据并将其加载到 DynamoDB 表
实施步骤
我们将逐步完成部署上图的步骤和配置
1-使用以下配置创建 Lambda 函数
从头开始的作者
函数名称:ParserDemo
运行时:Python 3.1x
其余保留默认
创建 Lambda 后,您需要修改超时配置和执行角色,如下所示:
我编写了这个Python代码来执行逻辑
import json import boto3 s3_client = boto3.client('s3') dynamodb = boto3.resource('dynamodb') def lambda_handler(event, context): bucket_name = event['Records'][0]['s3']['bucket']['name'] # Getting the bucket name from the event triggered by S3 object_key = event['Records'][0]['s3']['object']['key'] # Getting the Key of the item when the data is uploaded to S3 print(f"Bucket: {bucket_name}, Key: {object_key}") response = s3_client.get_object( Bucket=bucket_name, Key=object_key ) # We will convert the streamed data into bytes json_data = response['Body'].read() string_formatted = json_data.decode('UTF-8') #Converting data into string dict_format_data = json.loads(string_formatted) #Converting Data into Dictionary # Inserting Data Into DynamoDB table = dynamodb.Table('DemoTable') if isinstance(dict_format_data, list): #check if the file contains single record for record in dict_format_data: table.put_item(Item=record) elif isinstance(dict_format_data, dict): # check if the file contains multiple records table.put_item(Item=data) else: raise ValueError("Not Supported Format") # Raise error if nothing matched
2- 创建 S3 存储桶
BucketName:使用唯一的名称
将其余配置保留为默认值
将创建的 S3 存储桶作为触发器添加到 lambda 函数,如下所示:
3- 使用以下配置在 DynamoDB 中创建表
表名称:DemoTable
分区键:UserId
桌子设置:定制
容量模式:已配置
为了节省成本,将预配置容量单位配置为低值读/写(1 或 2 个单位)
现在设置已准备就绪,您可以通过将文件上传到 S3 来测试它,然后您将找到在 DynamoDB 表上创建的项目以及您上传到文件中的记录。
Lambda 函数的 CloudWatch Logs
DynamoDB 项目
我希望您觉得这很有趣,如果您有任何意见,请告诉我。
参考
S3 API
DynamoDB API
AWS 服务的 boto3 实践
以上是使用 Lambda 函数从 So DynamoDB 解析和加载数据的详细内容。更多信息请关注PHP中文网其他相关文章!

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,减法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

列表sandnumpyArraysInpyThonHavedIfferentMemoryfootprints:listSaremoreFlexibleButlessMemory-效率,而alenumpyArraySareSareOptimizedFornumericalData.1)listsStorReereReereReereReereFerenceStoObjects,withoverHeadeBheadaroundAroundaroundaround64bytaround64bitson64-bitsysysysyssyssyssyssyssyssysssys2)

toensurepythonscriptsbehavecorrectlyacrycrossdevelvermations,登台和生产,USETHESTERTATE:1)Environment varriablesforsimplesettings,2)configurationFilesForefilesForcomPlexSetups,3)dynamiCofforAdaptapity.eachmethodofferSuniquebeneiquebeneiquebeneniqueBenefitsaniqueBenefitsandrefitsandRequiresandRequireSandRequireSca

Python列表切片的基本语法是list[start:stop:step]。1.start是包含的第一个元素索引,2.stop是排除的第一个元素索引,3.step决定元素之间的步长。切片不仅用于提取数据,还可以修改和反转列表。

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/删除,2)储存的二聚体和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,请考虑performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3 Linux新版
SublimeText3 Linux最新版

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

SublimeText3汉化版
中文版,非常好用

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。