MST

星途 面试题库

面试题:Redis ASC和DESC在复杂数据结构排序中的应用

假设有一个Redis哈希表,存储了不同城市的温度数据,其中哈希表的字段是城市名称,值是一个包含最高温度、最低温度和平均温度的子哈希表。现在需要根据平均温度对这些城市进行升序和降序排序,应该如何借助Redis的ASC和DESC选项实现?说明实现思路并给出大致的代码示例(可以使用任何你熟悉的Redis客户端语言)。
18.6万 热度难度
数据库Redis

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 从Redis哈希表中获取所有城市的温度数据。
  2. 提取每个城市的平均温度,并存储在一个数组中。
  3. 使用Redis的ZADD命令将城市名称和对应的平均温度添加到有序集合中。
  4. 根据需求,使用ZRANGE(升序)或ZREVRANGE(降序)命令从有序集合中获取排序后的城市列表。

代码示例(Python + redis - py)

import redis

# 连接Redis
r = redis.Redis(host='localhost', port=6379, db=0)

# 获取哈希表中所有城市的温度数据
city_temperatures = r.hgetall('city_temperatures')

# 创建有序集合
sorted_cities_by_avg_temp = 'sorted_cities_by_avg_temp'
r.delete(sorted_cities_by_avg_temp)

for city, temp_data in city_temperatures.items():
    sub_hash = r.hgetall(temp_data)
    avg_temp = float(sub_hash[b'avg_temp'])
    r.zadd(sorted_cities_by_avg_temp, {city.decode('utf - 8'): avg_temp})

# 升序排序获取城市列表
asc_sorted_cities = r.zrange(sorted_cities_by_avg_temp, 0, -1, withscores=True)
print("升序排序后的城市及平均温度:", asc_sorted_cities)

# 降序排序获取城市列表
desc_sorted_cities = r.zrevrange(sorted_cities_by_avg_temp, 0, -1, withscores=True)
print("降序排序后的城市及平均温度:", desc_sorted_cities)