顧客を文字列として保存する代わりに、ハッシュとして保存する必要があります。Redis のハッシュの ziplist エンコーディングは、スペース効率が非常に優れています。70 を超える要素を格納している場合hash-max-ziplist-entriesは、redis.conf の制限を上げることを検討する必要があります
SORTRedis ハッシュを使用していると、楽しいことができます。SORTwith GETandを使用するSTOREことで、顧客からすべての都市を取得し、それらをリストとして保存できます (個別ではありません)。lpop次に、リストに対してandを呼び出して、リストをセットに変換できsaddます。
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して個別の都市のセットを取得することもできますが、メモリ効率が低下します。