简体   繁体   English

在Redis中存储两组表

[英]Store two sets of tables in redis

Using Python and redis api; 使用Python和Redis API;

I want to store a Dictionary such as 我想存储一个字典,例如

Value -> List of Words(L.O.W)
Each word in L.O.W -> Value

Basically i want everything to be searchable (in the best possible manner) to and fro but since redis doesn't support multiple table/records, how would we handle this in redis ? 基本上,我希望所有内容都可以(以最佳方式)来回搜索,但是由于redis不支持多个表/记录,我们将如何在redis中处理呢?

PS: I'm considering redis is the best choice to do so and i'm new to python as well PS:我认为Redis是这样做的最佳选择,我也是python的新手

The straightforward approach is to use two types of Sets: one for storing the value->LOW and once for the opposite direction, word from LOW->values. 直接的方法是使用两种类型的集合:一种用于存储value-> LOW,另一种用于相反的方向,即LOW-> values中的单词。

SADD val1 low1 low2
SADD val2 low2 low3
SADD low1 val1
SADD low2 val1 val2
SADD low3 val2

For the value->LOW, I think there are two viable options: 对于value-> LOW,我认为有两个可行的选择:

1) Store the LOW as a set with the value as the key name. 1)将LOW作为值存储为一组,并将其值作为键名称。 In redis-py this may look something like this: redis-py可能看起来像这样:

import redis
db = redis.StrictRedis() # Put connection info here
...
...
db.sadd(value, *listOfWords) # Assuming listOfWords is an iterable object (list, set, etc.)

#To recover the LOW for a given value:
listOfWords = db.smembers(value)

2) Store all value->LOW lookups as a hash whose key/value pairs are your "value" and a "serialized" list of words respectively. 2)将所有value-> LOW查找存储为哈希,其键/值对分别为您的“值”和“序列化”单词列表。 The top-level hash would be given a key name to make sure its function is obvious (in the example below I chose value_low_lookup : 顶级哈希将被赋予一个关键字名称,以确保其功能显而易见(在下面的示例中,我选择了value_low_lookup

db.hset(`value_low_lookup`, value, ';'.join(listOfWords))

#Recovering the LOW
listOfWords = db.hget('value_low_lookup', value).split(';')

Option #2 is more memory efficient in terms of storage in Redis, but requires more processing on the client side (pull out the semicolon-concatenated string and separate it into the list of words). 选项2在Redis中的存储方面具有更高的内存效率,但是需要在客户端进行更多处理(拉出分号连接的字符串并将其分成单词列表)。 You would also have to perform uniqueness-guarantees (if that's a requirement) client-side prior to insertion into Redis. 在插入Redis之前,您还必须在客户端执行唯一性保证(如果需要)。

For the LOW->value, I think a hash may be the most efficient way to represent that in Redis, similar to option #2 above. 对于LOW->值,我认为散列可能是在Redis中表示该散列的最有效方法,类似于上面的选项2。 The key/value pairs in this hash could be a word and the value associated to the LOW from which the word came, respectively. 此哈希中的键/值对可以分别是一个单词和与该单词来自的LOW关联的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM