Node Redis: Get First 10 Keys (Detailed Guide w/ Code Examples)

Use Case(s)

In Node.js applications using Redis as a database, one common use case is fetching the initial subset of keys for pagination or to limit the number of results returned from a large dataset.

Code Examples

Here's how you can do it using node-redis.

Example 1:

const redis = require('redis'); const client = redis.createClient(); client.keys('*', (err, keys) => { if (err) throw err; // Get the first 10 keys let firstTenKeys = keys.slice(0, 10); console.log(firstTenKeys); });

This example lists all keys in the Redis store and slices the first 10. It's simple, but not very efficient for large datasets because it fetches all keys before slicing.

Best Practices

  1. Use SCAN instead of KEYS for production code where there are many keys. KEYS can block the server when it is used against large databases. SCAN provides a cursor-based iteration which is more efficient and doesn't block the server.

Common Mistakes

  1. Using KEYS in a production environment: The KEYS command can be resource-intensive and slow down your Redis server, especially when dealing with large amounts of data. It's recommended to use SCAN for such scenarios.


Q: What's the difference between KEYS and SCAN?

A: KEYS returns all the keys matching a pattern at once, which can block the Redis server if it's dealing with large datasets. SCAN, on the other hand, uses a cursor to incrementally iterate over the keys, minimizing the impact on performance.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.