本指南演示了使用 Python 将数据高效插入 AWS DynamoDB,重点关注大型数据集。 我们将介绍:表创建(如果需要)、随机数据生成和批量写入,以实现最佳性能和节省成本。 需要 boto3
库;使用pip install boto3
安装它。
1。 DynamoDB 表设置:
首先,我们建立一个 AWS 会话并定义 DynamoDB 表的区域:
import boto3 from botocore.exceptions import ClientError dynamodb = boto3.resource('dynamodb', region_name='us-east-1') table_name = 'My_DynamoDB_Table_Name'
create_table_if_not_exists()
函数检查表是否存在,如果不存在,则使用主键 (id
) 创建它:
def create_table_if_not_exists(): try: table = dynamodb.Table(table_name) table.load() print(f"Table '{table_name}' exists.") return table except ClientError as e: if e.response['Error']['Code'] == 'ResourceNotFoundException': print(f"Creating table '{table_name}'...") table = dynamodb.create_table( TableName=table_name, KeySchema=[{'AttributeName': 'id', 'KeyType': 'HASH'}], AttributeDefinitions=[{'AttributeName': 'id', 'AttributeType': 'S'}], ProvisionedThroughput={'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5} ) table.meta.client.get_waiter('table_exists').wait(TableName=table_name) print(f"Table '{table_name}' created.") return table else: print(f"Error: {e}") raise
2。随机数据生成:
我们将使用 id
、name
、timestamp
和 value
生成示例记录:
import random import string from datetime import datetime def generate_random_string(length=10): return ''.join(random.choices(string.ascii_letters + string.digits, k=length)) def generate_record(): return { 'id': generate_random_string(16), 'name': generate_random_string(8), 'timestamp': str(datetime.utcnow()), 'value': random.randint(1, 1000) }
3。批量数据写入:
batch_write()
函数利用 DynamoDB 的 batch_writer()
进行高效的批量插入(每批最多 25 个项目):
def batch_write(table, records): with table.batch_writer() as batch: for record in records: batch.put_item(Item=record)
4。主要工作流程:
main函数统筹建表、数据生成、批量写入:
def main(): table = create_table_if_not_exists() records_batch = [] for i in range(1, 1001): record = generate_record() records_batch.append(record) if len(records_batch) == 25: batch_write(table, records_batch) records_batch = [] print(f"Wrote {i} records") if records_batch: batch_write(table, records_batch) print(f"Wrote remaining {len(records_batch)} records") if __name__ == '__main__': main()
5。结论:
此脚本利用批量写入来优化大量数据的 DynamoDB 交互。 请记住调整参数(批量大小、记录计数等)以满足您的特定需求。 考虑探索高级 DynamoDB 功能以进一步增强性能。
以上是使用 Python 高效批量写入 DynamoDB:分步指南的详细内容。更多信息请关注PHP中文网其他相关文章!

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他们areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)删除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

toresolvea“ dermissionded”错误Whenrunningascript,跟随台词:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

ArraySaresificatificallyfasterthanlistsForoperationsBenefiting fromDirectMemoryAcccccccCesandFixed-Sizestructures.1)conscessingElements:arraysprovideconstant-timeaccessduetocontoconcotigunmorystorage.2)iteration:araysleveragececacelocality.3)

ArraySareBetterForlement-WiseOperationsDuetofasterAccessCessCessCessCessCessAndOptimizedImplementations.1)ArrayshaveContiguucuulmemoryfordirectAccesscess.2)列出sareflexible butslible dueTopotentEnallymideNamicizing.3)forlarargedAtaTasetsetsetsetsetsetsetsetsetsetsetlib

在NumPy中进行整个数组的数学运算可以通过向量化操作高效实现。 1)使用简单运算符如加法(arr 2)可对数组进行运算。 2)NumPy使用C语言底层库,提升了运算速度。 3)可以进行乘法、除法、指数等复杂运算。 4)需注意广播操作,确保数组形状兼容。 5)使用NumPy函数如np.sum()能显着提高性能。

在Python中,向列表插入元素有两种主要方法:1)使用insert(index,value)方法,可以在指定索引处插入元素,但在大列表开头插入效率低;2)使用append(value)方法,在列表末尾添加元素,效率高。对于大列表,建议使用append()或考虑使用deque或NumPy数组来优化性能。


热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

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

热门文章

热工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

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

记事本++7.3.1
好用且免费的代码编辑器