gpt4 book ai didi

lua - 在不指定 redis 键的情况下从 hashamp 访问值

转载 作者:IT王子 更新时间:2023-10-29 06:07:49 25 4
gpt4 key购买 nike

我想在不提供 key 的情况下从 redis 中的哈希访问具有给定模式的值。

例子

HSET myKey  va11 "Hello" val2 "Hi" Val3 "GooMorning" val4 "Good Evening"
HSET myKey2 va11 "one val2 "two" Val3 "three" val4 "four"

我有一组键,它们的值如上所述。有没有什么方法可以在不提供键的情况下检索值。

我只是想在不提供 key 的情况下检查 Good* 是否有任何值(value)。

最佳答案

我看到您正在使用“lua”标签 - 如果 LUA 不是必须的,请考虑以下使用 HVALS 的示例.我提供一些 redis-py要使用的代码:

import redis

# connect to local redis-server:6379
r = redis.Redis()
# initialize sample "myKey" hash
r.hmset("myKey", {'val1': "Hello", 'val2': "Hi", 'val3': "GoodMorning", 'val4': "Good Evening"})
# provide "starts with" pattern (this could obviously be a regex as well)
pattern = "Good"
# find all values starting with the pattern and return them
values_matching = filter(lambda x: x.startswith(pattern), r.hvals("myKey"))
# print values: ["GoodMorning", "Good Evening"]
print values_matching

您没有说您需要匹配值的键。如果你这样做,那么你应该查看 HGETALL命令。

编辑 阅读您的评论后:是的,您需要使用 HGETALL 遍历散列中的所有键/值.修改后的示例如下:

import redis

r = redis.Redis()
r.hmset("myKey", {'val1': "Hello", 'val2': "Hi", 'val3': "GoodMorning", 'val4': "Good Evening"})
pattern = "Good"
# use hgetall() to iterate over all key-value pairs and form values_matching by looking only at pairs where the value starts with "Good"
values_matching = dict([(k, v) for k, v in r.hgetall("myKey").iteritems() if v.startswith(pattern)])
# print values: {'val3': 'GoodMorning', 'val4': 'Good Evening'}
print values_matching

关于lua - 在不指定 redis 键的情况下从 hashamp 访问值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25022804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com