One common use case of getting all keys matching a particular pattern in Redis is when you want to fetch all keys that start, end or contain a certain substring. This can be very useful in scenarios where keys are named following a certain convention and you need to retrieve all keys belonging to a specific group.
Using the KEYS
command is one way to get all keys matching a pattern:
const redis = require('redis'); const client = redis.createClient(); client.keys('*pattern*', function (err, keys) { if (err) return console.log(err); for(var i = 0, len = keys.length; i < len; i++) { console.log(keys[i]); } });
In this code snippet, you connect to the Redis server using redis.createClient()
. Then, you use the keys('*pattern*')
function to get all keys that match the specified pattern.
Remember that KEYS
command can be resource-intensive on large databases. It's recommended to use SCAN
for such cases, which can be done as follows:
const redis = require('redis'); const client = redis.createClient(); let cursor = '0'; function scan() { client.scan(cursor, 'MATCH', '*pattern*', 'COUNT', '100', function(err, reply) { if(err) throw err; cursor = reply[0]; reply[1].forEach(function(key, i) { console.log(key); }); if(cursor === '0') { return console.log('Scan complete'); } else { return scan(); } }); } scan();
Here we're using the SCAN
command with a cursor to iteratively fetch keys matching the pattern.
Avoid using the KEYS
command in a production environment as it can potentially block the server while executing. Instead, prefer the SCAN
command, which provides an iterator that allows you to retrieve keys in a more controlled manner.
One common mistake is not handling the case when the KEYS
or SCAN
commands return an error. Always ensure to handle potential errors in your callbacks.
KEYS
or SCAN
commands?
A: No, Redis does not support full regex patterns in KEYS
or SCAN
commands. It supports only glob-style patterns like *
, ?
and [chars]
.Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.