简介:本文系统解析Python与NoSQL数据库的集成方案,涵盖主流数据库类型、驱动安装、CRUD操作、性能优化及典型应用场景,为开发者提供全流程技术指导。
NoSQL数据库以非关系型数据模型为核心,突破了传统SQL数据库的ACID限制,通过水平扩展和灵活的数据结构满足现代应用的高并发、低延迟需求。Python凭借其简洁语法和丰富的生态库,成为NoSQL数据库开发的理想语言,尤其在大数据处理、实时分析和微服务架构中展现显著优势。
from pymongo import MongoClient# 建立连接池(配置重试机制和超时参数)client = MongoClient('mongodb://localhost:27017/',maxPoolSize=50,socketTimeoutMS=30000,retryWrites=True)db = client.ecommerce # 获取数据库实例collection = db.products # 获取集合
# 插入文档(支持批量操作)products = [{"_id": 1, "name": "Laptop", "price": 999.99},{"_id": 2, "name": "Smartphone", "price": 699.99}]collection.insert_many(products)# 复杂查询(聚合管道示例)pipeline = [{"$match": {"price": {"$gt": 500}}},{"$group": {"_id": None, "avg_price": {"$avg": "$price"}}}]result = collection.aggregate(pipeline)
# 创建复合索引提升查询性能collection.create_index([("category", pymongo.ASCENDING),("price", pymongo.DESCENDING)])# 监控索引使用情况db.command("collstats", "products")["indexSizes"]
import redisr = redis.Redis(host='localhost', port=6379, db=0)# 有序集合操作(排行榜实现)r.zadd("leaderboard", {"Alice": 100, "Bob": 85})top3 = r.zrevrange("leaderboard", 0, 2, withscores=True)# 发布/订阅模式pubsub = r.pubsub()pubsub.subscribe("realtime_updates")for message in pubsub.listen():print(message["data"])
save 900 1配置每15分钟至少1次写操作时触发持久化appendonly yes实现实时写入,配合fsync everysec平衡性能与安全性redis-trib.rb创建包含3主3从的集群,Python客户端通过redis.Cluster自动路由请求
from cassandra.cluster import Clusterfrom cassandra.auth import PlainTextAuthProviderauth_provider = PlainTextAuthProvider(username='cassandra',password='cassandra')cluster = Cluster(['127.0.0.1'], auth_provider=auth_provider)session = cluster.connect('iot_data')# 创建时间序列表(预分区策略)session.execute("""CREATE TABLE sensor_readings (device_id text,reading_time timestamp,value double,PRIMARY KEY ((device_id), reading_time)) WITH CLUSTERING ORDER BY (reading_time DESC)""")
from cassandra.query import BatchStatement, ConsistencyLevelbatch = BatchStatement(consistency_level=ConsistencyLevel.QUORUM)for i in range(100):query = "INSERT INTO sensor_readings (device_id, reading_time, value) VALUES (%s, %s, %s)"batch.add(query, ('dev001', datetime.now(), random.uniform(20, 30)))session.execute(batch)
minPoolSize=5, maxPoolSize=100平衡资源占用与并发能力ConnectionPool实现长连接复用,配置max_connections=50TokenAwarePolicy路由策略减少网络跳数
# 使用motor实现MongoDB异步操作import motor.motor_asyncioasync def get_product(product_id):client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost')db = client.ecommercedocument = await db.products.find_one({"_id": product_id})return document# 使用aioredis处理Redis异步请求import aioredisasync def update_cache():redis = await aioredis.create_redis('redis://localhost')await redis.set('key', 'value')value = await redis.get('key')
本文通过技术原理解析、代码示例和架构设计,系统阐述了Python与NoSQL数据库的集成方案。开发者可根据业务场景选择合适的数据库类型,结合Python生态工具构建高性能、可扩展的现代应用系统。