Redis与关系型数据库Python查询效率异常:Redis性能偏低原因排查
Redis vs 其他数据库无索引查询性能分析
测试约束与前置说明
- Redis脚本使用pipelining批量执行命令,同时采用connectionpool最大化降低网络延迟
- 不使用Redis Search,本次测试仅验证无索引场景下的查询耗时
测试数据集
- 总数据量:600万条记录
- 字段:
primary_key、timestamp、temperature_value、sensor_id、sensor_status - 示例记录:
1, 2023-01-01 00:00:00.0, 20.28, 1, GOOD - Redis存储类型:Hash
测试方案
- 筛选条件:仅查询
sensor_id为(1,2,8)的数据 - 查询量级:1万、2万、4万、8万、16万、32万条记录
- 统计方式:每个量级执行10次取平均值,每次查询设置不同offset避免超出数据范围
- 对比数据库:Redis、MySQL、PostgreSQL、InfluxDB
各数据库测试代码片段
Redis
start_time = time.time() pipeline = connection.pipeline() for key in filtered_keys: pipeline.hgetall(key) values = pipeline.execute() end_time = time.time()
MySQL
start_time = time.time() # SELECT query query = f"SELECT * FROM {table_name} WHERE sensor_id IN ({sensor_ids_str}) LIMIT {Offset}, {Amount};" cursor.execute(query) # Execute the query and fetch the results results = cursor.fetchall() # Record the end time end_time = time.time()
PostgreSQL
start_time = time.time() select_query = f"SELECT * FROM {table_name} WHERE sensor_id IN ({sensor_ids_str}) OFFSET {random_offset} LIMIT {rows_amount};" cursor.execute(select_query) result = cursor.fetchall() end_time = time.time()
InfluxDB
sensor_ids = [1, 2, 8] sensor_ids_str = ' OR '.join([f"sensor_id='{sensor_id}'" for sensor_id in sensor_ids]) time1 = time.time() # Perform the SELECT query result = client.query(f'SELECT * FROM {measurement_name} WHERE ({sensor_ids_str}) LIMIT {num_points} OFFSET {random_offset};') time2 = time.time()
测试结果与疑问
- 核心现象:Redis作为内存数据库,带
sensor_id过滤的查询耗时反而最长——查询32万条记录时,Redis耗时不足12秒,PostgreSQL不足4秒 - 对比情况:未添加
sensor_id过滤时,Redis性能接近最优;添加过滤后,Redis变为最慢 - 当前疑问:测试中仅统计了批量获取已过滤keys的pipeline执行耗时,但结果依然不理想,寻求该现象的原因分析
内容的提问来源于stack exchange,提问作者Mateusz G
相关产品推荐
相关产品推荐

