Faster way to iterate all keys and values in db
See original GitHub issueI have a db with about 350,000 keys. Currently my code just loops through all keys and gets its value from the db.
However this takes almost 2 minutes to do, which seems really slow, redis-benchmark gave 100k reqs/3s.
I’ve looked at pipelining but I need each value returned so that I end up with a dict of key, value pairs.
At the moment I’m thinking of using threading in my code if possible to speed this up, is this the best way to handle this usecase?
Here’s the code I have so far.
import redis, timeit
start_time = timeit.default_timer()
count = redis.Redis(host='127.0.0.1', port=6379, db=9)
keys = api_count.keys()
data = {}
for key in keys:
value = count.get(key)
if value:
data[key.decode('utf-8')] = int(value.decode('utf-8'))
elapsed = timeit.default_timer() - start_time
print('Time to read {} records: '.format(len(keys)), elapsed)
Issue Analytics
- State:
- Created 5 years ago
- Comments:7 (1 by maintainers)
Top Results From Across the Web
Faster way to iterate all keys and values in redis db
First, the fastest way is doing all of this inside EVAL. Next, recommended approach to iterate all keys is SCAN. It would not...
Read more >Faster way to iterate all keys and values in db #984 - GitHub
I have a db with about 350,000 keys. Currently my code just loops through all keys and gets its value from the db....
Read more >Here's the most efficient way to iterate through your Pandas ...
Iterating through the key-value pair of dictionaries comes out to be the fastest way with around 280x times speed up for 20 million...
Read more >How to Iterate Through a Dictionary in Python
This tutorial will take you on a deep dive into how to iterate through a ... Dictionaries map keys to values and store...
Read more >ActiveRecord on MySQL— Iterating over large tables with ...
In this article, I'm going to demonstrate performance differences between two ways of iterating over the records in a MySQL database table with...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

Reducing the number of round trips to the server will certainly help. You can also take advantage of the
SCANcommand’s automatic pagination. Something like:Alternatively, you could make this even easier/faster if you used a single redis hash (dictionary) to store all of these keys and values. Then use a single
HGETALLcommand to retrieve the entire hash as a Python dictionary.By adding
count=1000000to your code it completes in about 8 seconds for about 550k keys. Thanks!