Best way to get range of keys using specific pattern in Redis

Viewed 247

I work with Redis but I need best way to get keys from Redis .

I need search by range of date (2020-06-01 to 2020-06-20) for every company_id (id is unique)

example of key stat:company:2:date:2020-06-13

I think to solve problem I get key for every day but if need 200 numbers of key .

It take many times and I make some operation with value before display user .

I try use scan & keys

Environment Ruby 2.7.0, Ruby on Rails 6.0.3 Redis

1 Answers

To save round-trips to redis you can use mget to fetch many keys at once, if there're only around 200 of these - you can even do it in one call:

require 'date'
company_ids = [:a, :b, :c]
today = Date.today

#generate your keys:
keys = company_ids.map{|cid| (1..20).map{|day| [cid, day]} }.flatten(1).map{|cid,day| "stat:company:#{cid}:date:#{today - day}" }

hash = keys.zip(redis.mget(*keys)).to_h
Related