redis - 如何在Redis中相交并找到不同的键

标签 redis analytics data-modeling intersect

我希望获得尽可能高效的 Redis 键列表。我们可以在 Redis 服务器上对此进行建模,但是我们喜欢这样,所以这是解决问题的正确方法。让我描述一下情况。

假设有一大组“客户”作为字符串存储在 Redis 中。

customer__100000
customer__100001
customer__100002

每个客户都有很多属性。其中包括他们居住的城市。每个城市也存储在 Redis 中。

city__New York
city__San Francisco
city__Washington DC

通过不同的过程,我最终会得到一组客户 key (预过滤器的交叉集)。一旦我有了这些 key ,我需要找出我在哪些不同城市中那些客户。我的最终目标是获取城市的名称,但是如果我可以获得可以提取城市名称的 key ,那也很好。

为了了解我在这里讨论的规模,假设我们要处理 200-300k 的客户,这些客户具有大约 70 个属性(城市是其中之一),每个属性在 50-100,000 之间。我想让它尽可能高效。

最佳答案

与其将客户存储为字符串,不如将其存储为散列。 Redis 的哈希 ziplist 编码非常节省空间。如果您要存储超过 70 个元素,您应该考虑提高 redis.conf 中的 hash-max-ziplist-entries 限制

当您使用 Redis 哈希时,您可以使用 SORT 做一些有趣的事情。通过将 SORTGETSTORE 结合使用,您可以从客户那里获取所有城市并将它们存储为列表(不区分)。然后,您可以通过对列表调用 lpopsadd 将列表转换为集合。

这是一个 Redis Lua 脚本示例:

-- a key which holds a set of customer keys
local set_of_customer_keys = KEYS[1]
-- a maybe-existing key which will hold the set of cities
local distinct_set = ARGV[1]
-- attribute to get (defaults to city)
local attribute = ARGV[2] or 'city'
-- remove current set of distinct_cities
redis.call("DEL", distinct_set)
-- use SORT to build a list out of customer hash values for `attribute` 
local cities = redis.call("SORT", set_of_customer_keys, "BY", "nosort", "GET", "*->"..attribute)
-- loop through all cities in the list and add them to the distinct cities set
for i, city in pairs(cities) do
  redis.call("SADD", distinct_set, city)
end
-- return the distinct cities
return redis.call("SMEMBERS", distinct_set)

您还可以保留一个 customer__100000__cities 集,它与客户的属性一起永久存储,并使用 sinter *customer_cities_keys 来获取一组不同的城市,但那将是内存效率较低。

关于redis - 如何在Redis中相交并找到不同的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16041042/

相关文章:

node.js - 错误 : ERR value is not an integer or out of range from redis. 调用 ('zcard' ,'myzset' ) 在 LUA 脚本中

javascript - Adobe DTM 中的过滤器链接跟踪问题

javascript - 如何知道 Google Analytics 何时保存数据

sql - 哪个数据库设计更好?

用于实时数据的 Cassandra 数据建模

java - 在 Hybris 电子商务上创建产品数据模型

redis - not in redis查询怎么写

node.js - 防止为 connect-redis session 设置 TTL 以允许 allkeys-lru 用于内存策略

python-3.x - 如何将列表作为 pandas 数据框中 groupby 函数的输入

mysql - 我应该选择哪个数据库?