You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Python 3中使用Redis,如何通过test1、test2获取对应的first、second?

通过值反向获取Redis中对应字段名(Python3实现)

方法一:遍历匹配键并解析(适用于数据量较小的场景)

Redis本身是键→值的单向存储结构,没有内置反向查询能力,需先匹配所有符合格式的键,再逐个取值对比,匹配成功后解析字段名。

实现步骤:

  1. 安装Redis Python客户端:
pip install redis
  1. 编写代码:
import redis

# 连接Redis(根据实际配置修改参数)
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)

def get_field_by_value(target_value):
    # 用scan遍历匹配格式的键,避免keys()阻塞Redis
    cursor = 0
    while True:
        cursor, keys = r.scan(cursor, match='field:*:code', count=100)
        for key in keys:
            current_value = r.get(key)
            if current_value == target_value:
                # 从键名中解析字段名
                return key.split(':')[1]
        if cursor == 0:
            break
    return None

# 测试
print(get_field_by_value('test1'))  # 输出: first
print(get_field_by_value('test2'))  # 输出: second

方法二:提前建立反向索引(推荐,性能更优)

若需频繁反向查询,建议存储原始键值对时同步建立值→字段名的反向映射,直接通过GET操作获取结果,无需遍历。

实现步骤:

  1. 存储数据时同步写入反向索引:
# 存储原始键值对
r.set('field:first:code', 'test1')
r.set('field:second:code', 'test2')

# 建立反向索引
r.set('value:test1', 'first')
r.set('value:test2', 'second')
  1. 查询时直接通过反向索引获取:
def get_field_by_value_fast(target_value):
    return r.get(f'value:{target_value}')

# 测试
print(get_field_by_value_fast('test1'))  # 输出: first
print(get_field_by_value_fast('test2'))  # 输出: second

注意事项

  • 方法一的scan()比keys()更安全,keys()会遍历所有键,数据量大时会阻塞Redis服务。
  • 方法二需维护反向索引一致性,原始值更新或删除时要同步操作反向索引。

内容的提问来源于stack exchange,提问作者Prox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 06:45:36